205
\$\begingroup\$

What happens when the CapsLock key on your keyboard doesn't have a notch in it?

"This hPPENS."

The goal of this program is to consistently emulate keyboard misses where each A press is replaced with CapsLock. Uppercase 'A's from the source should yield the same effect. When CapsLock is enabled, capitalization is reversed.

Test Cases

"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."

"Compilation finished successfully."
-> "CompilTION FINISHED SUCCESSFULLY."

"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
-> "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"

"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."

"aAaaaaAaaaAAaAa"
-> "" (Without the notch, no one can hear you scream)

"CapsLock locks cAPSlOCK"
-> "CPSlOCK LOCKS CPSlOCK"

"wHAT IF cAPSlOCK IS ALREADY ON?"
-> "wHt if CPSlOCK IS lreDY ON?"

The winning criterion is, as usual, the size of the submitted program's source code.

\$\endgroup\$
  • 113
    \$\begingroup\$ Welcome to the site! This is a nice first challenge, and unfortunately very relatable for me and my fT FINGERS. \$\endgroup\$ – James Mar 14 '18 at 18:29
  • 5
    \$\begingroup\$ suggested test case : teSTateSTateSTateST \$\endgroup\$ – Rod Mar 14 '18 at 18:44
  • 92
    \$\begingroup\$ If only the enter key also had a notch in it so this wouldn' \$\endgroup\$ – 12Me21 Mar 14 '18 at 19:33
  • 78
    \$\begingroup\$ t happen....... \$\endgroup\$ – 12Me21 Mar 14 '18 at 19:33
  • 24
    \$\begingroup\$ Literally joined this site to upvote "Without the notch, no one can hear you scream" \$\endgroup\$ – lucasvw Mar 15 '18 at 21:10

59 Answers 59

1
2
2
\$\begingroup\$

><>, 139 129 bytes

1vo   <
>>i:"z")?^:"A"^>~~>~1$-
^o+< >::"aA"@=?^=?^$v
^o-^?  ("^"$*48:v?@:<
^ vv? )"Z":v?(< >>o
  >  ^v  < >:0 )?^;
  :< ^v?( "a"

A language with no concept of "characters" is surely the right tool for the job :)

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

x86-64, 31 bytes

Conforms to the System-V calling convention, tested in Ubuntu 16.04. Takes input from a pointer to a null-terminated in rsi, and outputs the result as a null-terminated string in rdi. rdi is expected to pointer to a buffer that's already been allocated with sufficient size.

Disassembly for byte count:

   0:       31 d2                   xor    edx,edx
   2:       ac                      lods   al,BYTE PTR ds:[rsi]
   3:       88 c1                   mov    cl,al
   5:       24 df                   and    al,0xdf
   7:       3c 41                   cmp    al,0x41
   9:       75 05                   jne    10 <not_A>
   b:       80 f2 20                xor    dl,0x20
   e:       eb f2                   jmp    2 <loop>
  10:       2c 41                   sub    al,0x41
  12:       3c 19                   cmp    al,0x19
  14:       77 02                   ja     18 <not_ascii>
  16:       30 d1                   xor    cl,dl
  18:       91                      xchg   ecx,eax
  19:       aa                      stos   BYTE PTR es:[rdi],al
  1a:       84 c0                   test   al,al
  1c:       75 e4                   jne    2 <loop>
  1e:       c3                      ret

Commented Assembly (GAS):

.intel_syntax noprefix
.text
// rsi has the input char*, rdi has the output char*.
// Input char* is \0-terminated.
.global caps
caps:
    // Use this for xor mask.
    xor     edx, edx
// Loop is set up as a do-while loop.
loop:
    // al = *rdi++
    lodsb

    // Save the character we read into cl.
    // We use al because the instructions are shorter.
    mov     cl, al

    // Make upper case
    and     al, 0b11011111

    // 65 = 'A'
    cmp     al, 65
    jne     not_A
is_A:
    // Invert capitialization mask
    xor     dl,0x20
    // Continue
    jmp     loop

not_A:
    // Now we check if input character is ascii.
    // Basically, if (al-'A' > 'Z'-'A'), it's not ascii
    sub     al, 65
    cmp     al, 25

    ja      not_ascii
ascii:
    // Flip capitilization if necessary.
    xor     cl, dl

not_ascii:
    // Restore saved character that we read.
    // xchg is 1 byte, as opposed to mov, which is 2.
    xchg    ecx, eax

    // Write out the character to the output buffer.
    stosb

endloop:
    // If al == 0, break
    test    al, al
    jnz     loop

end:
    // Just return, we've already written out the null
    // character to the output string.
    ret

Testing code in C, takes the input string via the first command line argument, prints out the result string:

#include <stdio.h> //puts
#include <stdlib.h> //malloc, free
#include <string.h> //strlen

void caps(char* output, char* input);

int main(int argc, char** argv) {
    char* instr = argv[1];
    char* buf = malloc(strlen(instr) + 1);
    caps(buf, instr);

    // Print converted string.
    puts(buf);

    free(buf);
}
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 82 bytes

s->foldl((b,c)->c∈"aA" ? !b : (print(c+32isletter(c)sign('_'-c)b);b),s,init=1<0)

Explanation

De-golfed:

function f(s::String)::Bool
    foldl(s, init=false) do b, c
        if c ∈ "aA"
            return !b
        else
            print(c + 32 * (isletter(c) & b) * sign('_'-c))
            return b
        end
    end
end

foldl(f, s, init=false): takes a function f that maps a state and a Char c to a new state. Applys f repeatedly over each Char of the string s, always passing the state previously returned by f back to f. init is the initial state. Here the state represents whether caps-lock is on.

if c in "aA": If c is an upper- or lowercase 'a', just return the opposite state.

isletter(c) & b: Bool, returns true iff c is a letter and b indicates, that caps-lock is on.

sign('_'-c): -1 if c is lowercase, 1 if c is uppercase.

print(c + 32 * (isletter(c) & b) * sign('_'-c)): Bools act like 0/1 under simple arithmetic operations, so if caps-lock should have an effect, this either adds or substracts 32 from c, returning a Char with opposite case. Then just print that.

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

CJam, 31 bytes

q{_eu'A={;T!:T;}{_el_eu+|T=}?}%

Explanation

Loops through searching for a and non-a

Try it online!


CJam, 47 bytes

Slightly more fun version

[q'a'Aer'A/_2%\2/z)\;{_[el_eu]z{\(@|1=\}%e_}%]z

Try it online!

Explanation

This code has two parts.

[
               Part 1
 q                          -> Read all input as a single string
 'a'Aer                     -> Replace 'a' in string with 'A'
 'A/                        -> Split by 'A' leaving empty sets
 _                          -> Duplicate
 2%                         -> Get all rows where i%2 is 0
 \                          -> Swap top two elements of stack
 2/                         -> Split into array with groups of length 2
 z                          -> Zip/Transpose
 )\;                        -> Right uncons, swap and pop.

               Part 2
 {
  _[el_eu]                  -> Create an array containing the lower case and upper case version
  z                         -> Zip/Transpose
  {
   \                        -> Swap top two
   (                        -> Uncons left
   @                        -> Rotate top three elements of stack
   |                        -> Set union
   1=                       -> Get element at array indice 1 (Wraps)
   \                        -> Swap top two
  }%                        -> Map onto every element of string
  e_                        -> Flatten
 }%                         -> Map onto every element of array
]z                          -> Zip/Transpose

The first part splits the string by 'A' leaving any empty sets behind. For the string "baacadE" that will give the following array.

["b", "", "c", "dE"]

That way, all normal case elements are at even indices and reverse case are odd. Which After executing the rest of the first part gives the following.

[["b", "c"], ["", "dE"]]

The second part will take the odd half and reverse the case of every string. This is done with the set union operator |. So for the element "dE" It will do the following. Since the set union operator preserves the order of the elements found in the first string/array we can always assume the reverse case element will be the second one in the string/array.

["dE", "dD"]
["dD", "dE"]
["dD", "E", "d"]
["E", "d", "dD"]
["E", "dD"]
["E", "D"]
...
["D", "E", "eE"]
["D", "Ee"]
["D", "e"]

All That is left to do is zip up the two halves.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 3, 114, 101, 97 bytes

import re
print(''.join(i.swapcase()if j%2else i for j,i in enumerate(re.split('a|A',input()))))

Split on all a's and toggle the case on the odd parts

Thanks @ElPedro !

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Can reduce to 96 by not assigning input() to the variable s. Try it online! \$\endgroup\$ – ElPedro Mar 15 '18 at 13:11
  • \$\begingroup\$ Good one @ElPedro I will edit! \$\endgroup\$ – Rick Rongen Mar 15 '18 at 13:13
1
\$\begingroup\$

Chip, 64 bytes

,Ava
>B#
>C#.,Bb
>D##>Cc
>E##>Dd
`~+L^Ee
G~+)~vS
g,\-zm.
f{-F`~'

Try it online!

How it works

This is where I wish I could color-code the source. However, all of the below are full programs, and may be run on their own.

First things first, write a (slightly mangled) cat program.

 A-a

     Bb
     Cc
     Dd
     Ee
G
g
f--F

Now invert capitalization of all characters A-Za-z.

This is determined by:

  1. c & 0x1F != 0
    • Filter out anything whose low 5 bits are zero
    • This is done by the left most column and upper ~
  2. ((c & 0x1F) + 0x5) & ~0x1F == 0
    • Filter out anything, that when added to 5, carries into or beyond the 6th bit
    • This is done by the two # columns
  3. c & 0x40 != 0
    • Filter out anything that is less than 64
    • This is done by the lower ~

The program assumes it will receive no characters above 127.

The results are aggregated and, the inversion is done by the { at the bottom.

,Ava
>B#
>C#. Bb
>D## Cc
>E## Dd
`~+' Ee
G~<
g,\*
f{-F

But attach that to a toggle (T flip-flop) that is initially off. Now, the toggle decides whether to invert the capitalization, and the filter from above decides which characters to apply it to. Put a * above the m to toggle on every cycle.

,Ava
>B#
>C#. Bb
>D## Cc
>E## Dd
`~+' Ee
G~<
g,\-zm.
f{-F`~'

Toggle the toggle when we see an Aa, and suppress that character too. We have an Aa if the filter above says we have A-Za-z, and the low five bits equal one (c & 0x1F == 1).

,Ava
>B#
>C#.,Bb
>D##>Cc
>E##>Dd
`~+L^Ee
G~+)~vS
g,\-zm.
f{-F`~'
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 3, 100 bytes

def f(x):x=x.replace('A','a').split('a');return''.join(i.swapcase()if i in x[1::2]else i for i in x)

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Forth, 225 bytes

: d DUP ; : x SWAP ; : w WITHIN ; : a d d 65 = x 97 = OR ; : y d d 65 91 w x 97 123 w OR ; : ~ INVERT ; x VALUE s 0 VALUE f : l 0 DO I s + C@ a IF f ~ TO f THEN y IF f IF 32 XOR d THEN a ~ IF EMIT THEN ELSE EMIT THEN LOOP ; l

What happening:

: d DUP ;                     \ shortcut for duplicating value on stack
: a d d 'A' = SWAP 'a' = OR ;             \ testing, if char is 'a' or 'A'
: y d d 'A' '[' WITHIN SWAP 'a' '{' WITHIN OR ;   \ testing, if char is within letters
: ~ INVERT ;                      \ shortcut for negation
SWAP                          \ swap addr and len of the string after s" command
VALUE s                       \ pop addr to s
0 VALUE f                     \ write 0 to f(lag)
: l 0 DO                      \ declaration of loop named 'l' from 0 to len (len is laying on top of the stack, remember)
I s + C@                      \ push iteration number on stack and load char from s + iteration

        \ this IF is searching for 'a' or 'A'
a IF
    f ~ TO f              \ if we found 'a' or 'A', then flip the f(lag)
    THEN
y IF                      \ if char is letter
    f IF                  \ and f is set
    32 XOR d THEN             \ change case of symbol

    a ~ IF                \ if it's not 'a' or 'A' then print char
        EMIT
        THEN 
ELSE
    EMIT                  \ print char
THEN
LOOP ;

l

Try it online!

Actually code in tio is 285 bytes, but this is because Footer didn't work for defining string, so i had to include string definition in actual code.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 66 bytes

u;f(char*s){for(u=0;*s;s++)u^=6305%*s?!putchar(*s&64?*s^u:*s):32;}

Similar to another solution but doesn't use ctype functions.

-1 byte thanks to [ceilingcat]!

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Pyth, 21 bytes

ssm+Pdr2edcscR\AcQ\a2

Try it here

Explanation

ssm+Pdr2edcscR\AcQ\a2
           scR\AcQ\a   Split the input on 'a' and 'A'
          c         2  Split the blocks into pairs.
  m  d   d             For each pair...
   +P r2e              ... cAPSlOCK the second block.
ss                     Join the blocks together.
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Pyth, 19 bytes

s.e?%k2rb2b:Q"a|A"3

Try it here.

Saved one byte thanks to mnemonic.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Charcoal, 21 bytes

FS¿⁼a↧ι≦¬κ¿κι¿№αι↧ι↥ι

Try it online! Link is to verbose version of code. Explanation:

FS

Loop through each character in the line of input.

¿⁼a↧ι

Test whether it equals a in lower case.

≦¬κ

If so then logically negate k. (Note that for some reason Charcoal considers k's default value None to be truthy.)

¿κ

Otherwise check whether k is currently truthy.

ι

If so then just print the character.

¿№αι

Otherwise check whether the current character is an upper case letter.

↧ι

If it is then print it in lower case.

↥ι

Otherwise print it in upper case.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 2, 103, 97 bytes

import re
def f(s):print"".join(j.swapcase()if i%2else j for i,j in enumerate(re.split('a|A',s)))
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 3, 100 bytes

edit: save 3 bytes thanks to sonrad10! Thanks!

import re
x=re.split('A|a',input())
print(''.join(map(lambda s:x.index(s)%2and s.swapcase()or s,x)))

Try it online!

To be further golfed (probably).

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You could change from from re import * to import re and x=re.split(...) to save 3 bytes. \$\endgroup\$ – sonrad10 Mar 15 '18 at 11:25
0
\$\begingroup\$

APL (Dyalog Classic), 46 41 40 bytes

'aA'~⍨⊢819⌶⍨¨2|(⊢≠819⌶¨)+≠\∘(∨⌿'aA'∘.=⊢)

Try it online!

How??

  • 'aA'~⍨ - Remove all a's from ...
  • ⊢819⌶⍨¨2|(⊢≠819⌶¨) - ... the alternating upper-and-lower-case of the argument ...
  • +≠\∘ ... based upon ...
  • (∨⌿'aA'∘.=⊢) ... the position of a and/or A.
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Yabasic, 121 bytes

An anonymous function that takes input as a line of text from STDIN and outputs to STDOUT.

Line Input""s$
For i=1To Len(s$)
c$=Mid$(s$,i,1)
u$=Upper$(c$)
If u$="A"Then
d=!d
ElsIf d Then?u$;Else?Lower$(c$);Fi
Next

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

pwsh, 109 bytes

$Input|%{$i=$_[0]-ceq'a';$r='';foreach($s in $_.split('a')){$r+=($s.ToUpper(),$s.ToLower())[$i];$i=!$i};$r}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Haskell, 96 94 Bytes

(Unix Line Endings)

import Data.Char
t=toUpper
i c|c>'Z'=t c|0<1=toLower c
f(x:s)|t x=='A'=f$i<$>s|0<1=x:f s
f x=x
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @Laikoni Unfortunate. I've fixed that now at the cost of 16 more bytes, but realised I was counting Windows line endings as 2 bytes, so I've clawed back 3 bytes by switching to Unix line endings. \$\endgroup\$ – Pharap Mar 19 '18 at 23:05
0
\$\begingroup\$

Haskell, ~~199~~ 133 bytes

import Data.Char
l c|isUpper c=toLower c|1<2=toUpper c
f _""=""
f b(c:cs)|toLower c=='a'=f(not b)cs|1<2=(if b then l else id)c:f b cs

Run using f False "<string>"

Ungolfed version:

import Data.Char

flipCase c
    | isUpper c = toLower c
    | otherwise = toUpper c

f "" _ = ""
f b (c:cs)
    | toLower c == 'a' = f cs $ not b
    | True = (if b then flipCase else id) c:f b cs
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can replace cs by a single letter variable name and define f as an infix function. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:06
  • \$\begingroup\$ Also note that when requiring extra arguments for the function, those need to be counted too. In this case the default would be to add 8 bytes to the byte count for f False and a newline. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:10
  • \$\begingroup\$ Instead of using a boolean it is shorter to use 0 and 1. not b then becomes 1-b, b in the conditional becomes b>0 and f False just f 0. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:14
0
\$\begingroup\$

Pip, 22 bytes

(The SC operator was added because of this challenge.)

{LCaQ'a?xX!:ii?SCaa}Mq

Try it online!

Explanation

                        i is 0, x is empty string (implicit)
                     q  Read a line of input
{                  }M   Map this function to its characters:
 LCa                     The character, lowercased
    Q'a                  Is it equal to lowercase a?
       ?                 If so:
          !:i             Logically negate i in place (0 -> 1, 1 -> 0)
        xX                Repeat the empty string that many times (thus, always return
                          empty string when the character is a/A)
                         Else:
             i?           Is i truthy (1)? If so, caps lock is on, so return:
               SCa         The character, swap-cased
                          Else return:
                  a        The character, unchanged
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Excel VBA, 115 bytes

A declared subroutine that takes input, s of expected type variant/string and outputs to the range [A1].

Sub f(s)
For i=1To Len(s)
c=Mid(s,i,1)
u=UCase(c)
If u="A"Then d=Not d Else[A1]=[A1]+IIf(d,u,LCase(c))
Next
End Sub
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

K4, 49 bytes

Solution:

{@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}

Examples:

q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"The quick brown fox jumps over the lazy dog."
"The quick brown fox jumps over the lZY DOG."
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"Compilation finished successfully."
"CompilTION FINISHED SUCCESSFULLY."
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
"WhT Hppens when the CPSLOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"aAaaaaAaaaAAaAa"
""

Explanation:

Fairly heavy, will look at other answers to see if I can golf this down:

{@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"} / the solution
{                                               } / lambda with implicit input x
                                           x,"a"  / append "a" to input
                                          _       / lowercase
                                      "a"=        / boolean list where input is "a"
                                     &            / indices where true
                                   w:             / save as w
                                  |               / reverse
                                _/                / drop over (remove these indices from...)
 @[ ;                 ;        ]                  / apply [var;indices;function]
                       .q.upper                   / uppercase
                  -':w                            / deltas of w
                 &                                / where, builds list of ascending values
                @                                 / apply
      .q.mod[;2]                                  / mod 2 to generate boolean list
   x                                              / apply uppercase to input x at these locations

Notes:

Think I may have missed the point. I enabled/disable caps when an a is encountered. Passes the first test cases but not the ones where caps is apparently already enabled...

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Lua, 152 151 bytes

p=io.read()a=0s=""for c in p:gmatch"."do l=c:lower()if c:find"[aA]"then a=(a+1)%2 else s=s..((c:find"%A"or a==0)and c or l==c and c:upper()or l)end end

Try it online!


Explanation

p = io.read() -- reads the input
a = 0
s = ""
for c in p:gmatch"." do -- loops through the string 'p' (the input) calling each character 'c'
  l = c:lower() -- stores the lowercase version of 'c'
  if c:find("[aA]") then -- if 'c' is a lowercase or uppercase 'A'
    a = (a+1)%2 -- flip the value of 'a' between 0 and 1, from what I've seen it uses less space
  else
    s = s..((c:find("%A") or a==0) and c or l==c and c:upper() or l)
    s = s..   -- append to the string 's'
            (c:find("%A") or a==0)   -- if this is not a letter or the "reversion" is off
                                   and c or   -- then append 'c' else
                                            l==c and c:upper() or l   -- if 'c' is lowercase then append it as uppercase else append it as lowercase
  end
end

If you have any questions, feel free to ask and i'll try to answer.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Lua 5.3, 137 bytes

a=0s=""io.read():gsub(".",function(c)if c:find"[aA]"then a=not a else l=c:lower()s=s..(a and c or l==c and c:upper()or l)end end)print(s)

Try it online!


Notes:

My result was very similar to @Visckmart above. But I included the print(s) in my byte count. Also the try it online test uses Lua 5.1, where my final result is in Lua 5.3. To make my final answer run on the website linked above I had to add a single space in between defining a and s: a=0 s="" which make it 138 bytes when using Lua 5.1

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 3, 110 bytes

code_golf=lambda s:"".join([j.swapcase()if i&1else j for i,j in  enumerate(__import__('re').split(r"a|A",s))])
| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ You should use codeblock formatting so that the underscores in __import__ don't get interpreted as bolding. As for actual golfing, you can remove the code_golf= part, as anonymous functions are acceptable. You can also use an online interpreter like TIO so that people can test your code and it can auto-format your CGCC submission. Try It Online \$\endgroup\$ – Jo King Aug 8 '19 at 4:20
  • \$\begingroup\$ Some other golfing tips, the [] in the join is not needed and it is shorter to import the module outside of the lambda. Additionally, could you please add the score of your submission to the header? \$\endgroup\$ – Jo King Aug 8 '19 at 4:56
  • \$\begingroup\$ Welcome! It is recommended to add an explanation for your code, because code-only answers are usually automatically flagged as low-quality. \$\endgroup\$ – mbomb007 Aug 8 '19 at 14:41
  • \$\begingroup\$ ... and there are two spaces between for i,j in and enumerate( \$\endgroup\$ – pppery Aug 8 '19 at 14:42
0
\$\begingroup\$

Clojure, 256 bytes

Golfed

(require[clojure.string :refer :all])(def u upper-case)(defn f[x](if(=(u x)x)(lower-case x)(u x)))(defn i[a](="A"(u a)))(defn g[x](let[v(vec(map str x))](join""(filter(complement i)(reduce-kv(fn[c k e](if(i e)(concat(take k c)(map f(drop k c)))c))v v)))))

Ungolfed

(ns acapslock.core
  (:require [clojure.string :as str]))


(defn flip
  [x]
  (if (= (str/upper-case x) x) (str/lower-case x) (str/upper-case x)))

(defn isa
  [a]
  (or (= "a" a) (= "A" a)))

(defn foo 
  [x]
  (str/join "" (filter (complement isa) (reduce-kv (fn [coll idx elem] (if (isa elem)(concat (take idx coll) (map flip (drop idx coll))) coll)) (vec (map str x)) (vec (map str x))))))

Explanation

The solution works in two steps:

  • First, we go through the input character by character. If we find an a or an A, we flip the case of the rest of the string.

  • Then we filter out all a's and A's.

Tests

(ns acapslock.core-test
  (:require [clojure.test :refer :all]
            [acapslock.core :refer :all]))


(deftest a-test
  (testing "test cases"
    (is (= "" (foo "")))
    (is (= "The quick brown fox jumps over the lZY DOG." (foo "The quick brown fox jumps over the lazy dog.")))
    (is (= "CompilTION FINISHED SUCCESSFULLY." (foo "Compilation finished successfully.")))
    (is (= "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?" (foo "What happens when the CapsLock key on your keyboard doesn't have a notch in it?")))
    (is (= "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS." (foo "The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness.")))
    (is (= "" (foo "aAaaaaAaaaAAaAa")))
    (is (= "CPSlOCK LOCKS CPSlOCK" (foo "CapsLock locks cAPSlOCK")))
    (is (= "wHt if CPSlOCK IS lreDY ON?" (foo "wHAT IF cAPSlOCK IS ALREADY ON?")))

    )) 
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

05AB1E (legacy), 11 bytes

„AaS¡εNFš]J

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Gameboy Z80 Assembly, 186 bytes

f:
 ld b,0
l:
 ld a,[hli]
 ld c,a
 cp 65
 jp z,a
 cp 97
 jp z,a
 res 5,a
 sub 65
 cp 25
 ld a,c
 jp nc,o
 xor b
o:
 ld [de],a
 inc de
 cp 0
 jp nz,l
 ret
a:
 ld a,b
 xor 32
 ld b,a
 jp l

This answer was heavily influenced by Ian Chew's x86 assembly answer.

Commented version

; input in hl
; output in de
; b is used for the caps lock state, 00000000 = no capslock, 00100000 = capslock
; a and c are used for the character
f:
 ld b,0
loop:
; load a character from the input and advance the source pointer
 ld a,[hli]
;save character in c
 ld c,a
; check if character is 'a' or 'A'
 cp 65
 jp z,is_a
 cp 97
 jp z,is_a
; check if character is a letter by setting the 5th bit to zero and checking for the range 25..65
 res 5,a
 sub 65
 cp 25
; load the character back from c
 ld a,c
; if it is not a letter, simply output it
 jp nc,output
; if it is a letter, apply the current case swap
 xor b
; output the character and advance the destination pointer
output:
 ld [de],a
 inc de
; end of input?
 cp 0
 jp nz,loop
; return
 ret

is_a:
; change the case swap mask by xoring with 32
 ld a,b
 xor 32
 ld b,a
; continue the loop
 jp loop
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Julia, 107 bytes

let b=false;[c in"aA" ? b=!b : print(b&&isletter(c) ? c<'@' ? c+32 : c-32 : c) for c::Char=read(stdin)];end

Try it online!

The let block is unfortunate, but apperently julia's scope is broken and b is undefined otherwise.

Here's the same program but with loops instead of comprehension, and if instead of conditionals.

 let b=false # whether to invert charachters
# normally this would be "for c in read(stdin,String)", 
# but reading a byte array and converting the bytes to chars saves one (byte).
for c::Char in read(stdin)  
if c in "aA" 
   b = !b
else
   print(if b && isletter(c) 
            if c<'@' # capitalization check
               c+32  # ascii code shenanigans to change case
            else
               c-32
            end
         else
            c # c is not a letter or we aren't swapping
         end)
end
end
end
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to the site, and nice first answer! I've edited it slightly to include a link to both the language and TryItOnline, the online interpreter most answers use. I don't know Julia, but is is possible to remove some of the whitespace to golf a little? Also, for more specific tips, be sure to check out our Tips for golfing in Julia page \$\endgroup\$ – caird coinheringaahing Oct 30 at 0:43
  • \$\begingroup\$ @cairdcoinheringaahing whitespace is mandatory around ? and : in the conditional operator. I removed whitespace where I could. \$\endgroup\$ – binarycat Oct 30 at 2:33
1
2

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.