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.
fooandFooare 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 code-golf 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>
48 Answers 48
Pyth, (削除) 25 (削除ここまで) (削除) 21 (削除ここまで) 20 bytes
shM-crz1dc4."@YK1⁄21⁄4
Thanks to @Jakube for saving one byte!
Explanation
shM-crz1dc4."@YK1⁄21⁄4 # z = input rz1 # convert input to uppercase c d # split input on spaces c4."@YK1⁄21⁄4 # 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
-
\$\begingroup\$ A little string packing trick:
."@YK½¼saves one byte over"ANDORBYOF. It's basically@ANDBYOROFpacked. \$\endgroup\$Jakube– Jakube2016年03月13日 14:05:23 +00:00Commented Mar 13, 2016 at 14:05 -
\$\begingroup\$ Dang, the non-ascii-chars got deleted. Just pack
@ANDBYOROFand see what you get. \$\endgroup\$Jakube– Jakube2016年03月13日 14:07:49 +00:00Commented Mar 13, 2016 at 14:07 -
\$\begingroup\$ @Jakube Thanks! Tried to pack it before, but always ended up with the same length or longer. \$\endgroup\$Denker– Denker2016年03月13日 14:26:32 +00:00Commented Mar 13, 2016 at 14:26
Jelly, (削除) 21 (削除ここまで) 20 bytes
,"°ɲịĊs°gɗ»ṣ6ドルŒuḟ/Ḣ€
(-1 thanks to @Dennis.)
,"°ɲịĊs°gɗ» Pair input with the string "OR OF by AND"
ṣ6ドル 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...
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
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
-
\$\begingroup\$ I'm unfamiliar with retina. What does
T`l`Ldo? \$\endgroup\$Cyoce– Cyoce2016年03月14日 06:59:35 +00:00Commented Mar 14, 2016 at 6:59 -
\$\begingroup\$ @Cyoce See update with explanation \$\endgroup\$Andreas Louv– Andreas Louv2016年03月14日 12:58:49 +00:00Commented Mar 14, 2016 at 12:58
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
-
1\$\begingroup\$ putting .toUpperCase() before the regexp you could avoid the
iflag \$\endgroup\$edc65– edc652016年03月14日 07:44:06 +00:00Commented Mar 14, 2016 at 7:44 -
\$\begingroup\$ Pretty sure the parens are not needed here \$\endgroup\$Shaun H– Shaun H2016年03月15日 20:29:59 +00:00Commented Mar 15, 2016 at 20:29
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.
-
\$\begingroup\$
vimis a programming language \$\endgroup\$CousinCocaine– CousinCocaine2016年03月23日 20:36:04 +00:00Commented Mar 23, 2016 at 20:36
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.
-
\$\begingroup\$ Doesn't work for
Foo Offline Bar\$\endgroup\$Downgoat– Downgoat2016年03月13日 17:27:21 +00:00Commented Mar 13, 2016 at 17:27 -
\$\begingroup\$ General consensus is you don't need to assign the function to a variable. \$\endgroup\$Cyoce– Cyoce2016年03月14日 06:17:35 +00:00Commented Mar 14, 2016 at 6:17
-
\$\begingroup\$ putting .toUpperCase() before the regexp you could avoid the
iflag \$\endgroup\$edc65– edc652016年03月14日 07:44:43 +00:00Commented Mar 14, 2016 at 7:44
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!
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!
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.
-
\$\begingroup\$ This doesn't work for a case like
Android Cyber Enterprises. It ignores all words that happen to start with the pattern of one of the excluded words. \$\endgroup\$Xcali– Xcali2025年03月03日 15:18:24 +00:00Commented Mar 3 at 15:18
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.
Saved 2 bytes thanks to manatwork!
-
3\$\begingroup\$
.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']\$\endgroup\$manatwork– manatwork2016年03月13日 16:37:56 +00:00Commented Mar 13, 2016 at 16:37
Python, 81 bytes
lambda s:''.join(c[0]for c in s.upper().split()if c not in'AND OF OR BY'.split())
-
\$\begingroup\$ 76 bytes using set difference:
lambda s:''.join(c[0]for c in s.upper().split()if{c}-{'AND','OF','OR','BY'})\$\endgroup\$movatica– movatica2021年05月25日 10:07:30 +00:00Commented May 25, 2021 at 10:07
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.
-
-
2\$\begingroup\$ There's a problem. Using
$srequiresregister_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). \$\endgroup\$aross– aross2016年03月15日 14:52:47 +00:00Commented Mar 15, 2016 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;}
-
\$\begingroup\$ Sorry, but that
awkcall looks horrible. What about replacing it with${@^^}? \$\endgroup\$manatwork– manatwork2016年03月15日 11:29:35 +00:00Commented Mar 15, 2016 at 11:29 -
\$\begingroup\$ @manatwork, good point, didnot think of that... \$\endgroup\$rexkogitans– rexkogitans2016年03月15日 11:36:19 +00:00Commented Mar 15, 2016 at 11:36
-
\$\begingroup\$ Looks much better. Now please replace the
grepcall with[[ $i = @(AND|OR|BY|OF) ]]. ;) And with that you can also remove the " + GNU coreutils" part from the post header. \$\endgroup\$manatwork– manatwork2016年03月15日 11:37:57 +00:00Commented Mar 15, 2016 at 11:37 -
\$\begingroup\$ One more thing: you could replace the
echowithprintf. 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;}\$\endgroup\$manatwork– manatwork2016年03月15日 11:45:12 +00:00Commented Mar 15, 2016 at 11:45 -
\$\begingroup\$ I was looking for the bash notation similar to grep's
\bbut couldnot find it... And I did not know thatdo...donecan be replace by curly braces. \$\endgroup\$rexkogitans– rexkogitans2016年03月15日 12:01:05 +00:00Commented Mar 15, 2016 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
};
-
\$\begingroup\$ 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. \$\endgroup\$Aplet123– Aplet1232016年03月13日 15:20:10 +00:00Commented Mar 13, 2016 at 15:20
-
\$\begingroup\$ Also, you don't need
var. We don't worry about polluting the global scope in code golf :P \$\endgroup\$NinjaBearMonkey– NinjaBearMonkey2016年03月13日 15:24:33 +00:00Commented Mar 13, 2016 at 15:24 -
\$\begingroup\$ It does not work. If you look at the examples the input ` united states of america ` it gives the output ` usa ` not ` USA ` \$\endgroup\$Aplet123– Aplet1232016年03月13日 15:27:39 +00:00Commented Mar 13, 2016 at 15:27
-
\$\begingroup\$ Yeah, I noticed that. Stupid super long built-in function names. \$\endgroup\$clamchowder314– clamchowder3142016年03月13日 15:30:51 +00:00Commented Mar 13, 2016 at 15:30
-
\$\begingroup\$ You can set Z to
_.map(v=>/o(f|r)|and|by/.test(v)?"":v[0])instead of"". You can remove your_.forEach(p=>Z+=p[0].toUpperCase());line and replace yourreturn Zline withreturn Z.join("").toUpperCase()\$\endgroup\$Aplet123– Aplet1232016年03月13日 15:37:43 +00:00Commented Mar 13, 2016 at 15:37
MATL, (削除) 34 (削除ここまで) 27 bytes
1 byte fewer thanks to @AandN
KkYb'OF AND OR BY'YbX-c1Z)!
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\$\begingroup\$ Maybe this works with 33 bytes?
XkYb{'OF' 'AND' 'OR' 'BY'}X-c1Z)!\$\endgroup\$Adnan– Adnan2016年03月13日 12:35:26 +00:00Commented Mar 13, 2016 at 12:35
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.
-
\$\begingroup\$ Fail when And as part \$\endgroup\$l4m2– l4m22025年03月01日 04:49:02 +00:00Commented Mar 1 at 4:49
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"
-
\$\begingroup\$ Oh, that
.composition operator looks quite intuitive. I am just never sure what is evaluated in what order. \$\endgroup\$flawr– flawr2016年03月13日 19:34:05 +00:00Commented Mar 13, 2016 at 19:34 -
\$\begingroup\$ chapter 6 of Learn you a Haskell for Great Good! has a good introduction to function application with
$and composition with.. \$\endgroup\$nimi– nimi2016年03月13日 21:07:49 +00:00Commented Mar 13, 2016 at 21:07 -
1\$\begingroup\$ 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"]. \$\endgroup\$nimi– nimi2016年03月13日 22:06:47 +00:00Commented Mar 13, 2016 at 22:06 -
\$\begingroup\$ Now this is definitely over my head, I'm going to have to learn quicker=) \$\endgroup\$flawr– flawr2016年03月15日 09:55:58 +00:00Commented Mar 15, 2016 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.
-
2\$\begingroup\$ 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
inputvsraw_input, +2 forprint("".join..)vsprint"".join..) Also no space between a symbol and a keyword. \$\endgroup\$CalculatorFeline– CalculatorFeline2016年03月13日 19:03:40 +00:00Commented Mar 13, 2016 at 19:03 -
\$\begingroup\$ 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. \$\endgroup\$Denker– Denker2016年03月14日 03:39:52 +00:00Commented Mar 14, 2016 at 3:39
-
\$\begingroup\$ @CatsAreFluffy It might help to switch to Python 3, but I highly prefer Python 2 over it because who likes parentheses anyways? \$\endgroup\$mriklojn– mriklojn2016年03月14日 20:59:19 +00:00Commented Mar 14, 2016 at 20:59
-
\$\begingroup\$ 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. \$\endgroup\$Denker– Denker2016年03月14日 23:20:57 +00:00Commented Mar 14, 2016 at 23:20 -
\$\begingroup\$ Remove spaces between symbols and keywords(it works) \$\endgroup\$CalculatorFeline– CalculatorFeline2016年04月02日 18:55:16 +00:00Commented Apr 2, 2016 at 18:55
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
ß(binary11011111) for binaryANDinstead of a negated space (binary00100000).
R, (削除) 77 (削除ここまで) 75 bytes
cat(substr(w<-toupper(scan(,'')),1,1)[!grepl('^(AND|OR|OF|BY)$',w)],sep='')
-1 byte thanks to Dominic van Essen changing the indexing.
Reads from stdin. Takes the words, converts them to uppercase, removes those that are excluded from acronyms, extracts the first character from each, and prints them to the stdout.
-
\$\begingroup\$ 76 bytes...? \$\endgroup\$Dominic van Essen– Dominic van Essen2021年01月20日 21:53:00 +00:00Commented Jan 20, 2021 at 21:53
-
\$\begingroup\$ @DominicvanEssen very nice! And another byte down by setting
winline. \$\endgroup\$Giuseppe– Giuseppe2021年01月20日 21:56:35 +00:00Commented Jan 20, 2021 at 21:56
K (ngn/k), 34 bytes
{`c$-32+*'(" "\_x)^$`and`or`by`of}
_xlowercase the input(" "\...)split input on spaces(...)^$`and`or`by`ofremove and/or/by/of*'take the first character of each remaining word`c$-32+convert to uppercase
Mathematica, (削除) 132 (削除ここまで) 117 bytes
ToUpperCase[First/@Characters@DeleteCases[StringDelete[StringSplit@#,"of"|"and"|"or"|"by",IgnoreCase->True],""]<>""]&
15 bytes saved thanks to @CatsAreFluffy.
-
\$\begingroup\$ 1arg
StringSplitdefaults to splitting on whitespace (-5bytes) \$\endgroup\$CalculatorFeline– CalculatorFeline2016年03月13日 16:07:47 +00:00Commented Mar 13, 2016 at 16:07 -
1\$\begingroup\$ Also you can replace the word list with
"of"|"and"|"or"|"by". Also{"a","b","c"}<>""==StringJoin[{"a","b","c"}]. One last thing:Charactersautomatically maps over lists. \$\endgroup\$CalculatorFeline– CalculatorFeline2016年03月13日 16:11:50 +00:00Commented Mar 13, 2016 at 16:11 -
1\$\begingroup\$ The leaderboard would prefer that you put a comma after Mathematica. Also you're welcome :) \$\endgroup\$CalculatorFeline– CalculatorFeline2016年03月13日 16:20:44 +00:00Commented Mar 13, 2016 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.
-
\$\begingroup\$ Realized that would match Anderson and drop it. Added 4 bytes \$\endgroup\$Matt– Matt2016年03月14日 01:50:43 +00:00Commented Mar 14, 2016 at 1:50
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
-
\$\begingroup\$ Hey! I also made a Lua submission, here: codegolf.stackexchange.com/a/75616/33183. \$\endgroup\$Trebuchette– Trebuchette2016年03月16日 04:17:10 +00:00Commented Mar 16, 2016 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!
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)
-
\$\begingroup\$ Wow, totally forgot the existence of
%w! That's a great one! \$\endgroup\$Katenkyo– Katenkyo2016年03月16日 07:37:44 +00:00Commented Mar 16, 2016 at 7:37 -
\$\begingroup\$ Katenkyo: Well, this would also work with
%a;%amatches letters, and%wmatches letters and numbers. The main thing is using a custom function ingsub. \$\endgroup\$Trebuchette– Trebuchette2016年03月16日 17:02:27 +00:00Commented Mar 16, 2016 at 17:02 -
\$\begingroup\$ Yeah, I see that it is easier to remove
AND OR BY OFwhen selecting words... I used no custom function because they cost a lot, so I thoughgsub("(%a)%a+",string.upper)after removing them would have been better \$\endgroup\$Katenkyo– Katenkyo2016年03月17日 07:22:01 +00:00Commented Mar 17, 2016 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
-
\$\begingroup\$ 18 bytes by using an uppercase string of words to avoid (and searching for a permutation that compresses well...) \$\endgroup\$Dominic van Essen– Dominic van Essen2021年01月20日 21:40:55 +00:00Commented Jan 20, 2021 at 21:40
T` l) \$\endgroup\$