39
\$\begingroup\$

Because of this, you need a better way of working out if a phrase is an acronym of a word. You also think it would be worthwhile to see if the phrase and word in question are recursive acronyms.

Your task:

Given a word and then a phrase separated by a line, output if the phrase is an acronym and then if it is a recursive acronym. (The phrase contains what it stands for)

  • The input will compose of alphabetical characters as well as spaces.
  • Your program shouldn't be case sensitive.

Example Input/Output:

Case 1:

Input:

Acronyms
Acronyms can really obviously narrow your message sensors

Output:

True 
True

Case 2:

Input:

FAQ
frequently asked questions

Output:

True 
False

Case 3:

Input:

foo
bar baz

Output:

False
False

Case 4:

Input:

GNU
GNU is not Unix

Output:

False
False

Case 5:

Input:

Aha
A huge Aha

Output:

True
True
\$\endgroup\$
12
  • 73
    \$\begingroup\$ Acronyms Can Recurse? Oh! Now You're Making Sense. \$\endgroup\$
    – Geobits
    Oct 19 '15 at 17:04
  • 2
    \$\begingroup\$ No, just as long as it's clear what the output is \$\endgroup\$
    – Blue
    Oct 19 '15 at 18:05
  • 9
    \$\begingroup\$ This reminds me of an XKCD: xkcd.com/917 \$\endgroup\$ Oct 19 '15 at 18:14
  • 1
    \$\begingroup\$ Related. \$\endgroup\$ Oct 19 '15 at 18:25
  • 5
    \$\begingroup\$ ABCDE: Another basic clearly defined example. \$\endgroup\$ Oct 20 '15 at 5:08

24 Answers 24

11
\$\begingroup\$

Pyth, 19 18

&pqJrz0hCKcrw0)}JK

This prints the result in a rather odd format, like: TrueFalse.

You can try it online or run the Test Suite.

Explanation:

&pqJrz0hCKcrw0)}JK      :
    rz0    rw0          : read two lines of input, and convert each to lower case
          c   )         : chop the second input on whitespace
   J     K              : store the first line in J and the chopped second line in K
  q    hC               : zip K and take the first element, check if it is the same as J
 p                      : print and return this value
&              }JK      : and the value with whether J is in K, implicit print
\$\endgroup\$
0
15
\$\begingroup\$

Python 3, 89

Saved a bunch of bytes thanks to SOPython.

a=input().lower()
d=input().lower().split()
h=tuple(a)==next(zip(*d))
print(h,h&(a in d))

The most complicated part of this solution is h=tuple(a)==next(zip(*d)).
This unpacks the list d into zip and then calls next to return a tuple of the first element of each iterable passed into zip which is then compared against a tuple of each letter in a (tuple(a)).

\$\endgroup\$
1
  • \$\begingroup\$ You can save 7 bytes by substituting [0]==l for .startswith(l). \$\endgroup\$
    – Skyler
    Oct 19 '15 at 17:47
7
\$\begingroup\$

CJam, 21 20 bytes

qeuN/)S/_:c2$s=_p*&,

Try this fiddle in the CJam interpreter or verify all test cases at once.

How it works

qeu                  e# Read from STDIN and convert to uppercase.
   N/                e# Split at linenfeeds.
     )S/             e# Pop the second line form the array.
      S/             e# Split it at spaces.
        _:c          e# Push a copy and keep on the initial of each word.
           2$s       e# Push a copy of the line array and flatten it.
                     e# This pushes the first line.
              =      e# Check for equality.
               _p    e# Print a copy of the resulting Boolean.
                 *   e# Repeat the word array 1 or 0 times.
                  &  e# Intersect the result with the line array.
                   , e# Push the length of the result (1 or 0).
\$\endgroup\$
4
\$\begingroup\$

Haskell, 81 80 bytes

import Data.Char
f[a,b]|c<-words b=(a==map(!!0)c,elem a c)
p=f.lines.map toLower

The output format is not strictly defined, so I return a pair of booleans, e.g. p "Aha\na huge arm" -> (True,False).

\$\endgroup\$
1
  • \$\begingroup\$ Today I learned of pattern guards (<-)—thanks! \$\endgroup\$
    – wchargin
    Oct 21 '15 at 5:13
4
\$\begingroup\$

Scala, 135 110 108 bytes

val Array(x,y)=args.map(_.toLowerCase)
val z=y.split(" ").map(_(0)).mkString
print(z==x,z==x&&y.contains(z))

Saved a few bytes by using command line arguments (thanks to J Atkin for the hint), putting the booleans out as a tupel, using mkString instead of new String and print instead of println.

EDIT: Misinterpreted the question, and had to reimplement the solution

\$\endgroup\$
0
3
\$\begingroup\$

Python 3, 106 bytes

Well, at least it beat Scala ;)

x=input().lower()
y=input().lower().split()
g=all(x[i]==y[i][0]for i in range(len(y)))
print(g,g&(x in y))
\$\endgroup\$
5
  • 1
    \$\begingroup\$ @muddyfish Possibly more explanation of each examples would prevent this from happening to other people. \$\endgroup\$
    – Beta Decay
    Oct 19 '15 at 17:41
  • \$\begingroup\$ Would more time in the sandbox have helped? In my (obviously rather limited) experience of it, you only get responses whilst it's nearly at the top \$\endgroup\$
    – Blue
    Oct 19 '15 at 18:07
  • \$\begingroup\$ @muddyfish Well I don't know how long you left it so, I don't know \$\endgroup\$
    – Beta Decay
    Oct 19 '15 at 18:26
  • \$\begingroup\$ I left it there for about a day \$\endgroup\$
    – Blue
    Oct 19 '15 at 18:28
  • \$\begingroup\$ @muddyfish A week is the recommended norm \$\endgroup\$
    – Beta Decay
    Oct 19 '15 at 18:28
3
\$\begingroup\$

AppleScript, 302 301 297 293 Bytes

Aw, hell yeah. Not even bothered that I lose, this is competitive for AppleScript.

set x to(display dialog""default answer"")'s text returned
set y to(display dialog""default answer"")'s text returned's words
set n to y's items's number
repeat n
try
if not y's item n's character 1=(x as text)'s character n then return{false,false}
end
set n to n-1
end
return{true,x is in y}

Outputs as:

{true, false}

Or whatever the answer happens to be.

\$\endgroup\$
0
2
\$\begingroup\$

PHP, 120 bytes

Not being case sensitive is a lot of weight (26 bytes). Passed all test cases:

foreach($c=explode(' ',strtolower($argv[2]))as$l)$m.=$l[0];var_dump($x=$m==$a=strtolower($argv[1]),$x&&in_array($a,$c));

Outputs two bool values in this form:

bool(true)
bool(false)

Reads two arguments from the command line, like:

a.php Acronyms "Acronym can really obviously narrow your message sensors"

Ungolfed

$acronym = strtolower($argv[1]);
$words = strtolower($argv[2]);
$words = explode(' ', $words);

foreach($words as $word) {
    $letters .= $word[0];
}

$isAcronym = $letters == $acronym;

var_dump(
    $isAcronym,
    $isAcronym && in_array($acronym, $words)
);
\$\endgroup\$
2
\$\begingroup\$

Ruby, 77 74 bytes

b=gets.chop.upcase
a=gets.upcase
p c=a.scan(/\b\w/)*''==b,c&&a.include?(b)
\$\endgroup\$
1
\$\begingroup\$

Ruby, 52 bytes

p !!gets[/^#{x=gets.scan(/\b\w/)*""}$/i],!! ~/#{x}/i

Example:

$ echo "Aha
A huge AHA" | ruby acronym.rb
true
true
\$\endgroup\$
1
\$\begingroup\$

Matlab, 90 bytes

function z=f(r,s)
z=[sum(regexpi(s(regexpi(s,'(?<=(\s|^))\S')),r))>0 nnz(regexpi(s,r))>0];

Example (note that Matlab displays true/ false as 1/ 0):

>> f('Aha', 'A huge Aha')
ans =
     1     1
\$\endgroup\$
1
\$\begingroup\$

JavaScript ES6, 95 92 bytes

(a,b)=>[(r=eval(`/^${a}$/i`)).test((s=b.split` `).map(c=>c[0]).join``),s.some(c=>r.test(c))]

Input both strings as parameters. Outputs an array with two values: one for each boolean.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I wouldn't have thought of using a regex in place of .indexOf. Nice work! Perhaps r=eval(`/^${a}$/i`) would work in place of your current r setup. \$\endgroup\$ Oct 21 '15 at 21:29
  • \$\begingroup\$ @ETHproductions And I in turn wouldn't have thought of eval as a RegExp object shortener. Thanks for the tip! \$\endgroup\$
    – Mwr247
    Oct 22 '15 at 14:54
0
\$\begingroup\$

GNU sed, 118 bytes

Requires -r flag, included in score as +1. Note that I'm using \b for a word-boundary match, even though I can't find this documented in GNU sed. It Works For Me...

N
h
s/^(.*)\n.*\b\1\b.*/True/i
/\n/s/.*/False/
x
:
s/(.)(.*\n)\1[^ ]* ?/\2/i
t
/../s/.*/False/
/F/h
/F/!s/.*/True/
G

Expanded:

#!/bin/sed -rf

N
h

# Is it recursive?
s/^(.*)\n.*\b\1\b.*/True/i
# If no replacement, there's still a newline => false
/\n/s/.*/False/

x

# Is it an acronym?
# Repeatedly consume one letter and corresponding word
:
s/(.)(.*\n)\1[^ ]* ?/\2/i
t
# If more than just \n remain, then false
/../s/.*/False/
# And falsify recursive, too
/F/h
# !False => true
/F/!s/.*/True/

G
\$\endgroup\$
0
\$\begingroup\$

Groovy, 91 bytes

a=args*.toLowerCase()
println([a[1].split()*.charAt(0).join("")==a[0],a[1].contains(a[0])])

Output format is [bool, bool].This takes it's input from the command line args.

\$\endgroup\$
0
\$\begingroup\$

Lua 5.3, 182 bytes

a=""b=io.read c=a.lower d=a.reverse e=d(c(b()))f=~e:len()h=a.sub g=d(c(b()))for m in g:gmatch"[^ ]+"do f=-~f if h(e,f,f)~=h(m,~0)then break end k=k or m==e end f=f>~1print(f,f and k)
\$\endgroup\$
0
\$\begingroup\$

R, 93 bytes

a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))

Usage:

> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
Aha
A huge Aha
Read 3 items
TRUE TRUE
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
Acronyms
Acronyms can really obviously narrow your message sensors
Read 8 items
TRUE TRUE
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
FAQ
frequently asked questions
Read 3 items
TRUE FALSE
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
foo
bar baz
Read 2 items
FALSE FALSE
\$\endgroup\$
0
\$\begingroup\$

awk 137 bytes

awk 'BEGIN{T="True";F="False"}NR*NF<2{a=tolower($1)}END{for(i=1;i<=NF;i++)b=b substr(tolower($i),1,1);print(a==b?T:F)"\n"(a==tolower($1)?T:F)}'
  • Initialize T="True";F="False" to simplify output.
  • NR*NF<2{a=tolower($1)}: set a only if the first line only has one field.
  • END{...}: assuming only two lines...
    • for(i=1;i<=NF;i++)b=b substr(tolower($i),1,1): construct recursive acronym.
    • print(a==b?T:F)"\n"(a==tolower($1)?T:F): print the output of both comparisons, a==b and a==tolower($1).

If anyone knows how to optimize the recursive acronym construction, feel free to suggest.

\$\endgroup\$
0
\$\begingroup\$

SpecBAS - 144 bytes

1 INPUT a$,b$: LET a$=UP$(a$),b$=UP$(b$),d$="": DIM c$(SPLIT b$,NOT " ")
2 FOR EACH w$ IN c$(): LET d$=d$+w$(1): NEXT w$
3 TEXT d$=a$'POS(a$,b$)>0

Converting the 2 x inputs to uppercase saves characters vs. lowercase conversion. Can now have multiple assignments done in one LET statement, which also helps. And TEXT saves one character over PRINT.

Uses 1/0 to show true/false (the apostrophe just moves output to the next line).

\$\endgroup\$
0
\$\begingroup\$

Perl5, 90 bytes

($a,$b)=map{chomp;lc}<>;print((join"",map{substr($_,0,1)}split/ /,$b)ne $a?0:($b=~$a?2:1))

cheating a bit: 0 = all false, 1 = one true, 2 = both true. I'm not a golfer, but am upset perl is missing while browsing!

($a,$b)=map{chomp;lc}<>;              # get the two lines as lowercase
print((                               #
join"",map{substr($_,0,1)}split/ /,$b # collapse first letters of secondline
     ) ne $a  ? 0 : ( $b=~$a ? 2 : 1))# 0 nothing, 1 not recursive, or 2 
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6) 93

(w,s)=>s[L='toLowerCase'](w=w[L](z=y='')).replace(/\w+/g,v=>y+=v[z=z||v==w,0])&&[y=y==w,y&&z]

Test running the snippet below in any EcmaScript 6 compliant browser

f=(w,s)=>s[L='toLowerCase'](w=w[L](z=y='')).replace(/\w+/g,v=>y+=v[z=z||v==w,0])&&[y=y==w,y&&z]

// TEST

out=x=>O.innerHTML+=x+'\n';

;[
 ['Acronyms', 'Acronyms can really obviously narrow your message sensors', true, true]
,['FAQ', 'frequently asked questions', true, false]
,['foo', 'bar baz', false, false]
,['GNU', 'GNU is not Unix', false, false]
,['Aha', 'A huge Aha', true, true]
,['Lolcat', 'Laughing over lolcat captions and tearing.', true, true]
,['ABCDE', 'Another basic clearly defined example.', true, false]
,['GNU', 'Gnus nettle unicorns', true, false]
,['PHP', 'PHP Hypertext Preprocessor', true, true]
].forEach(([a,b,c,d]) => (
  [r,s]=f(a,b), 
  out(((r==c && s==d)?'OK ':'KO ') + a + ',' + b + ' -> ' + f(a,b))
))
<pre id=O></pre>

\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 89 96 95 bytes

(a,b)=>[p=(a=a[l='toLowerCase']())==(c=b[l]().split` `).map(x=>x[0]).join``,p&&c.some(x=>x==a)]

Shucks...I thought I had it all sorted out, but apparently I was wrong.

This defines an anonymous function which takes input as two strings, and returns and array of two boolean items. The first item is calculated by comparing the the first string in all lowercase with the first char of each word in the second string. The second item is calculated simply by checking if the second string contains the first.

Here's another solution for the second item; 2 bytes shorter, but very few browsers support it:

p&&c.includes(a)
\$\endgroup\$
4
  • \$\begingroup\$ Checking if the second string contains the first fails for GNU: Gnus nettle unicorns \$\endgroup\$
    – edc65
    Oct 21 '15 at 22:48
  • \$\begingroup\$ Please check again: tried it and does not even work: ReferenceError: l is not defined (missing l= before toLowerCase) \$\endgroup\$
    – edc65
    Oct 21 '15 at 22:54
  • \$\begingroup\$ ... fixed that bug, it fails for 'GNU','GNU is not unix' (test case 4) should be false, false \$\endgroup\$
    – edc65
    Oct 21 '15 at 22:56
  • \$\begingroup\$ @edc65 Shucks, I erased the l= while looking for a bug and forgot to put it back. Thanks for bringing that up! The other test case should be fixed as well. \$\endgroup\$ Oct 21 '15 at 23:09
0
\$\begingroup\$

Pyke (was untitled when posted), (noncompetitive), 20 bytes

l1c"jFh)J"iQl1qDji{&

You can find the source code here, language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 8)

Or 18 bytes (stableish)

l1idcmhsRl1jqDji{&

Try it here!

\$\endgroup\$
0
\$\begingroup\$

Jelly, 13 bytes

ŒlḲḢ€⁼ɗ,wɗ/«\

Try it online!

Takes input as a pair [phrase, word]. +2 bytes to input as a newline separated pair with the word first

If the inputs were always in a single case, then this much more elegant program would work for 9 bytes.

This outputs the pair [a, b], where a and b are truthy values (1) or falsey values (0). The Footer in the TIO link runs the code over each test case.

How it works

ŒlḲḢ€⁼ɗ,wɗ/«\ - Main link. Takes [phrase, word] on the left
Œl            - Convert both to lowercase
         ɗ    - Group the previous 3 links into a dyad, f(phrase, word):
      ɗ       -   Group the previous 3 links into a dyad, g(phrase, word):
  Ḳ           -     Split the phrase on spaces
   Ḣ€         -     Take the first characters of each word
     ⁼        -     Does this equal the word?
        w     -   Index of word as a sublist of phrase, or 0 if not found
       ,      -   Pair; Yield [g(phrase, word), index]
          /   - Reduce [phrase, word] by f, yielding f(phrase, word)
           «\ - Scan by minimum

It is possible for word to be a sublist of phrase, but not an acronym (for example, [GNU is not Unix, GNU]. In this case, f returns [0, 1] which isn't a valid output. Additionally, w returns a non-zero integer, rather than 1/0, any we want to turn this into 1.

Therefore, we scan f's return by « (minimum), which transforms it:

[g(phrase, word), index] «\ = [g(phrase, word), min(g(phrase, word), index)]

This zeros out any trailing 1s, and converts [1, x] (where x > 0) into [1, 1]

\$\endgroup\$
0
\$\begingroup\$

AWK, 107 bytes

$0=tolower($0){a="True"}b{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);$0=(b==f?a:c)"\n"(e?a:c)}!b{b=$1}f

Try it online!

Here's a different take using GAWK... The code defines four conditions with associated code blocks. The order they are evaluated when each line is read in matters in this case, to save a couple of characters.

The first condition,

$0=tolower($0)

is always true given the possible inputs. The check is really unimportant here, the side effect of translating the input line to lowercase it what we care about. The code run just sets variable a to the string True to shorten the code.

{a="True"}

The second condition,

b

is true only for the second input line, since b isn't set until the first line is processes. So it's essentially a shortcut for NR>1.

{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);e=e?a:c;$0=(b==f?a:c)"\n"e}

The code block is two statement, first a for loop that processes each word in the input stream. The top of loop statement,

c="False"

is just setting up c as a shortcut for False to save characters. Putting here saves a character, since the ; is already there.

The "should I iterate" test,

$++d

sets d to the current word and stops when we run off the end of the line. And the bottom of the loop statement,

e+=b==$d

increments e everytime the current word matches the acronym from the first line (which is in b).

Finally, the body of the loop appends the first character of the current word to f, which will end up being the acronym associated with the line.

f=f substr($d,1,1)

Once the loop is done, the output $0 is set by concatenating two ternary.

$0=(b==f?a:c)"\n"(e?a:c)

The (b==f?a:c) part is True or False depending on whether or not the provided and constructed acronyms match. And the second part,

(e?a:c)

is True or False based on how many words in the second line matched the acronym from the first line.

The third condition applied to each line just sets b to the value of the first line, setting b only if is hasn't been set already.

!b{b=$1}

And the last condition is true only after the second line has been processed.

f

It uses the default action for unspecified code block. So it's a shortcut for NR>1{print$0}.

One caveat: I'm not 100% clear on the rules of the contest. If the second condition depends on the first, meaning only valid acronyms can be recursive acronyms, this slightly longer version is necessary.

$0=tolower($0){a="True"}b{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);$0=(g?a:c)"\n"(e&&(g=b==f)?a:c)}!b{b=$1}f
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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