29
\$\begingroup\$

OCTOBER 22 IS INTERNATIONAL CAPS LOCK DAY! UNFORTUNATELY, SOME DO NOT RECOGNIZE THE GLORY OF THE ALMIGHTY CAPS LOCK. THEY SAY IT SEEMS "OBNOXIOUS" OR "LIKE SHOUTING" OR SOME NONSENSE. IN ORDER TO CONFORM TO THESE OBVIOUSLY ILLOGICAL AND INANE COMPLAINTS, PLEASE WRITE ME A PROGRAM THAT TURNS NORMAL TEXT INTO "SENSIBLE" OR "REASONABLE" TEXT TO MAKE PEOPLE STOP COMPLAINING.

Description

The input and output for your solution will both be strings that contain only printable ASCII characters.

The input string will contain zero or more caps lock runs. A caps lock run (or CLR for short) is defined as the following:

  • The CLR must contain no lowercase letters (a-z), except as the first character of a word.

    • A word, for the purposes of this challenge, is a sequence of non-spaces. So, PPCG, correcthorsebatterystaple, and jkl#@_>00()@#__f-023\f[ are all considered words.
  • The CLR must also contain at least one space; hence, it must be at least two words.

  • Each of the words in the CLR must contain at least two letters (A-Za-z).

    • Note that this refers to the CLR taken by itself, without any surrounding characters that may not have been included in the CLR. For example, foO Bar is not a CLR because the string O B by itself has words with less than two letters.

CLRs should be parsed "greedily"—that is, you should always find the longest CLRs possible.

Once you have identified all of the CLRs in the input string, swap the case of all letters inside of the CLRs and output the resulting string.

Test cases

The first line is input, and the second is output. Bolded portions of the input are substrings that are considered CLRs.

CAPS LOCK IS THE BEST!
caps lock is the best!
I really LOVE pROGRAMMING pUZZLES AND cOde Golf!
I really love Programming Puzzles and Code Golf!
This is a challenge on PPCG. This is a test CASE. TEST
This is a challenge on PPCG. This is a test case. test
LorEM iPSUM DOLoR sIT amet, conSECTETur ADIPISciNG eLIT. MAECENAS iD orci
Lorem Ipsum doloR sIT amet, conSECTETur ADIPIScing Elit. maecenas Id orci
;'>}{/[]'"A*(389971(*(#$&B#@*(% c'>#{@D#$! :,>/;[e.[{$893F
;'>}{/[]'"a*(389971(*(#$&b#@*(% C'>#{@d#$! :,>/;[e.[{$893F
iT'S cAPS lOCK DAY!!! cELebraTE THis WONDERFUL key
It's Caps Lock day!!! Celebrate this WONDERFUL key
aBcDE fGHIj KLmNO pQrST (uVwXY) ZZ___Zz__Z
aBcde Fghij KLmno PqrST (uVwxy) zz___zz__Z
#aA# aA
#aA# aA

Rules

  • You may assume that the input will never contain two or more spaces in a row, and that it will never contain a leading or trailing space.

  • 20% bonus (multiply your code length by .8) if your entire code is a CLR. ;) (mostly just for fun, since it's unlikely that the winning submission will have this bonus)

  • This is , so the shortest code in bytes wins.

\$\endgroup\$
  • 17
    \$\begingroup\$ Please, stop shouting. \$\endgroup\$ – TheDoctor Oct 22 '15 at 21:37
  • 4
    \$\begingroup\$ Also, for test case #3, wouldn't the capitalized PPCG get lowercased too? (PPCG. T contains a space) \$\endgroup\$ – TheDoctor Oct 22 '15 at 21:38
  • 7
    \$\begingroup\$ CAPS LOCK IS HOW I FEEL INSIDE RICK. ALL THE TIME. \$\endgroup\$ – Dennis Oct 22 '15 at 21:47
  • 2
    \$\begingroup\$ @Dennis I read that in Morty's voice (from Rick and Morty), b/c he's talking to "Rick". \$\endgroup\$ – mbomb007 Oct 22 '15 at 21:48
  • 1
    \$\begingroup\$ "bonus points for your code being a CLR" just makes me want to do this in LOLCODE... \$\endgroup\$ – cat Oct 22 '15 at 22:26
4
\$\begingroup\$

CJam, 100 86 83 81 bytes

Ml{_,),{1$<_S/(4$!>\1f>s+_eu=*S%_{'[,_el^:Af&s,2<},!*1>},_{W=/(AA26m>er}{;(}?\s}h

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

Algorithm

  1. Identify the longest possible CLR that starts with the first character.

  2. If it exists, swap its case, print it, and remove it from the beginning of the string.

    Else, remove a single character from the beginning of the string, and print it unmodified.

  3. If there are more characters left, go back to step 1.

How it works

Ml         e# Push an empty string and a line from STDIN.
{          e# Do:
  _,       e#   Copy the string on the stack and compute its length (L).
  ),       e#   Push [0 ... L].
  {        e#   Filter; for each integer I in that array:
    1$<    e#     Copy the string and keep its first I characters.
    _S/    e#     Push a copy and split at spaces.
    (      e#     Shift out the first word.
    4$!    e#     Push the logical NOT of the fifth topmost item of the stack.
           e#     This pushes 1 for the empty string on the bottom, and 0
           e#     for non-empty strings and printable characters.
    >      e#     Remove that many characters from the beginning of the first word.
           e#     This will remove the first character iff the string on the
           e#     stack is the entire input. This is to account for the fact that
           e#     the first word is not preceded by a space.
    \1f>   e#     Remove the first character of all remaining words.
    s+     e#     Concatenate all of them.
    _eu=   e#     Convert a copy to uppercase and check for equality.
    *      e#     Repeat the I characters 1 or 0 times.
    S%_    e#     Split at runs of spaces, and push a copy.
    {      e#     Filter; for each non-empty word:
      '[,  e#       Push the string of all ASCII characters up to 'Z'.
      _el  e#       Push a copy and convert to lowercase.
      ^    e#       Perform symmetric difference, pushing all letters (both cases).
      :A   e#       Store the result in A.
      f&s  e#       Intersect A with each character of the word. Cast to string.
      s    e#       This removes all non-letters from the word.
      ,2<  e#       Count the letters, and compare the result to 2.
    },     e#     If there are less than 2 letters, keep the word.
    !      e#     Push the logical NOT of the result.
           e#     This pushes 1 iff all words contain enough letters.
    *      e#     Repeat the array of words that many times.
    1>     e#     Remove the first word.
  },       e#   Keep I if there are still words left.
  _{       e#   If at least one I was kept:
    W=     e#     Select the last (highest) one.
    /      e#     Split the string on the stack into chunks of that length.
    (      e#     Shift out the first chunk.
    AA26m> e#     Push "A...Za...z" and "a...zA...Z".
    er     e#     Perform transliteration to swap cases.
  }{       e#   Else:
    ;      e#     Discard the filtered array.
    (      e#     Shift out the first character of the string on the stack.
  }?       e#
  \s       e#   Swap the shifted out chunk/character with the rest of the string.
}h         e# If the remainder of the string is non-empty, repeat.
| improve this answer | |
\$\endgroup\$
  • 5
    \$\begingroup\$ How it works: plays 20 E# notes on the piano. \$\endgroup\$ – kirbyfan64sos Oct 25 '15 at 2:30
  • \$\begingroup\$ I've added a few more details. :P \$\endgroup\$ – Dennis Oct 25 '15 at 3:17
2
\$\begingroup\$

Perl, 96 82 80 bytes

-pe'$y=qr/[^a-z ]{2,}|\b\S[^a-z ]+/;s#$y( $y)+#join$,,map{uc eq$_?lc:uc}$&=~/./g#eg'

Passes all tests. Assumes input from STDIN, prints to STDOUT.

How it works:

  • setup a regex ($y) that matches

    • at least two non-lowercase, non-whitespace characters OR
    • a word boundary, followed by a non-whitespace character, followed by one or more non-lowercase, non-whitespace characters
  • match multiple instances of space-separated strings that match $y, use s/// to invert case

I'm sure there's room for improvement. If there is a way to get rid of the whole join-map-split deal there may still be a chance to qualify for the bonus :)

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save a few bytes by using a-z instead of [:lower:]. Also, -pe is usually counted as 1 byte, and the single quotes as zero bytes. \$\endgroup\$ – Dennis Oct 23 '15 at 13:54
  • \$\begingroup\$ @Dennis : Thanks for the suggestion! That allowed me to simplify the code somewhat - down to 81 as per your guidelines about Perl one-liners \$\endgroup\$ – Zaid Oct 23 '15 at 17:27
  • \$\begingroup\$ This answer is invalid, since it doesn't pass the last test case (recently added courtesy of Dennis). \$\endgroup\$ – Doorknob Oct 24 '15 at 16:44
2
\$\begingroup\$

Javascript, 193

decapslock =

a=>a.replace(/(^[a-z][^a-z ]+|[^a-z ]{2,})( [a-z][^a-z ]+| [^a-z ]{2,})+/g,b=>b.split` `.some(f=>f.split(/[a-z]/i).length<3)?b:b.split``.map(e=>e==(E=e.toUpperCase())?e.toLowerCase():E).join``)
<!-- Snippet UI -->
<input placeholder='sAMPLE tEXT' oninput="document.getElementsByTagName('p')[0].innerText=decapslock(this.value)" />
<p></p>

Explanation:

a=>a.replace(/* giant regex */,
  b=>
    b.split` `.some(
      f=>
        f.split(/[a-z]/i).length < 3   // check for 2+ letters
    )
      ? b                              // .some() immediately returns true if it's invalid
      : b.split``.map(                 // otherwise it's valid, so flip case
          e=>
            e == (E = e.toUpperCase()) // is it uppercase?
              ? e.toLowerCase()        // change it to LC
              : E                      // change it to UC, which was already done for
                                       // the case check
            ).join``
        )
(
^[a-z][^a-z ]+ // check for a CLR starting at the beginning with LC
|
[^a-z ]{2,}    // check for a CLR that begins in the middle of a word or starts at the
               // beginning with UC
               // in both cases, 2+ letters are required
)
(
 [a-z][^a-z ]+ // check for the next word of the CLR, starting with LC
|
 [^a-z ]{2,}   // check for the next word of the CLR, starting with UC
)+             // check for 1 or more next words
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ This answer is invalid, since it doesn't pass the last test case (recently added courtesy of Dennis). \$\endgroup\$ – Doorknob Oct 24 '15 at 16:44
  • \$\begingroup\$ Argh, the fix added tons of bytes to this. But, it's fixed \$\endgroup\$ – DankMemes Oct 25 '15 at 0:53

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.