229
\$\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\$
20
  • 125
    \$\begingroup\$ Welcome to the site! This is a nice first challenge, and unfortunately very relatable for me and my fT FINGERS. \$\endgroup\$
    – DJMcMayhem
    Mar 14, 2018 at 18:29
  • 100
    \$\begingroup\$ If only the enter key also had a notch in it so this wouldn' \$\endgroup\$
    – 12Me21
    Mar 14, 2018 at 19:33
  • 85
    \$\begingroup\$ t happen....... \$\endgroup\$
    – 12Me21
    Mar 14, 2018 at 19:33
  • 30
    \$\begingroup\$ Literally joined this site to upvote "Without the notch, no one can hear you scream" \$\endgroup\$
    – lucasvw
    Mar 15, 2018 at 21:10
  • 9
    \$\begingroup\$ I LSO WISH THt my keyboRD Hd a bigger bCKSPce kwt==et=y \$\endgroup\$ Mar 16, 2018 at 20:58

65 Answers 65

3
\$\begingroup\$

Javascript (ES6), 80 79 bytes

(Partly based off of this answer by Rick Hitchcock. Posting as a separate answer because I don't have sufficient reputation to comment.)

(Saved 1 byte thanks to @l4m2's post here.)

a=>a.replace(j=/a()|./gi,(c,o=c[`to${j^c>{}?'Low':'Upp'}erCase`]())=>(j^=!o,o))
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Laikoni
    Mar 19, 2018 at 9:16
2
\$\begingroup\$

Python 3, 78 72 bytes

import re
lambda x:re.sub("[Aa](.*?)(a|A|$)",lambda m:m[1].swapcase(),x)
\$\endgroup\$
6
  • \$\begingroup\$ You can use m[1] in place of m.group(1) on Python 3.6+. \$\endgroup\$
    – Bubbler
    Mar 15, 2018 at 0:04
  • \$\begingroup\$ Why was this flagged as low quality…? \$\endgroup\$
    – Nissa
    Mar 15, 2018 at 0:21
  • \$\begingroup\$ I have no idea ... \$\endgroup\$ Mar 15, 2018 at 0:22
  • 1
    \$\begingroup\$ New posts are flagged automatically if they are short and contain no text. Adding a description usually prevents that. \$\endgroup\$
    – mbomb007
    Mar 15, 2018 at 0:35
  • \$\begingroup\$ And now I wonder how many "A"s there are supposed to be in "ppperry". \$\endgroup\$
    – Mr Lister
    Mar 15, 2018 at 11:03
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 :)

\$\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);
}
\$\endgroup\$
2
\$\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.

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

SM83, 29 28 bytes; Z80, 30 29 bytes

  • SM83 version
06 00 2A 4F CB AF D6 41
28 0C FE 1A 79 30 01 A8
12 13 B7 20 ED C9 78 EE
20 47 18 E6
  • Z80 version (changes in stars)
06 00 *7D 23* 4F CB AF D6 41
28 *0E* FE 1A 79 30 *03* A8
12 13 B7 20 *EE* C9 78 EE
20 47 18 *E7*

Disassembly and explanation

fun:
    ld b,0      ; 06 00     we start out in non-swapping state
loop:
#ifdef SM83
    ld a,(hl+)  ; 2A        load character
#else
    ld a,(hl)   ; 7D
    inc hl      ; 23        Z80 doesn't have autoinc addressing
#endif
    ld c,a      ; 4F        save copy in c
    res 5,a     ; CB AF     Clear bit 5
    sub 65      ; D6 41     subtract 'A'
    jr z,is_a   ; 28 0C/0E  if 0, was 'A' or 'a'; handle that later
    cp 26       ; FE 1A     compare to 26
    ld a,c      ; 79        reload from copy
    jr nc,put   ; 30 01/03  skip next if was letter (<26)
    xor b       ; A8        xor in caps lock setting
put:
    ld (de),a   ; 12        store
    inc de      ; 13        and increment
    or a        ; B7        check if zero by self-or (cheap trick)
    jr nz,loop  ; 20 ED/EE  loop if wasn't 0
    ret         ; C9        and return otherwise
is_a:
    ld a,b      ; 78
    xor 32      ; EE 20
    ld b,a      ; 47        flip caps lock setting
    jr loop     ; 18 E6/E7  jump back to loop

Heavily based on corvus_192's answer. The differences:

  • I counted bytes of machine code, not assembly
  • I changed jp (absolute jump, three bytes) to jr (relative jump, two bytes), saving five bytes
  • I moved the case-fold (res 5,a) to before the test for A, saving a compare-to-constant and a jump (four more bytes saved)
  • This produced the sequence cp 65; jr z,is_a; sub 65, which can be collapsed to sub 65; jr z,is_a, saving two more bytes.
  • It's cheaper to test if a is 0 by executing or a (and a also works) than cp 0; it doesn't tell you sign, but we didn't need that.

In total, these changes (well, not the counting difference) save twelve bytes from the original.

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

Swift, 110 bytes

import Darwin
var x=0,f={for c in($0+"").utf8{c&95==65 ?(x^=1,0).1:putchar(CInt(x>0&&66...90~=c&95 ?c^32:c))}}

f(_:) is the closure you want.

If you're on Linux instead of macOS, you can replace import Darwin with import Glibc to save a byte (and you have to do it anyway if you want it to compile). For platform independence, import Foundation can be used instead.

This is an almost direct port of @KevinCruijssen's Java answer to Swift, with:

  • some things shuffled around,
  • a call to ~=(lhs:rhs:) (the pattern matching operator) to condense the range check,
  • a tuple shenanigan to let us use the ternary conditional operator instead of if-else, and
  • a bit of C interop abuse because Swift names are long.

Notes

  • CInt is a typealias for Int32, the type expected by putchar(_:) (for reasons beyond my mortal comprehension; C is weird).

  • For reasons slightly closer to a realm I can grasp (i.e. exit codes), putchar(_:) also returns an Int32, meaning we can't directly put a call to it in a ternary conditional that expects Void (an alias for ()), which is the result type of x^=1 (because, in Swift, assignment operators rightfully don't return anything).

    So, instead, I shoved x^=1 into a tuple and added 0 as the second element, and then accessed it with .1. This still evaluates x^=1, but returns an Int32 (the type the 0 literal is inferred as) rather than a Void, which calms down the type checker a bit.

  • The ~=(lhs:rhs:) operator is used internally for custom pattern matching (i.e. switch statements, if case, and the like). There's an overload defined on ClosedRange that checks if rhs is contained in lhs. We abuse that here.

  • Because Swift really doesn't want you to do things like this with an ordinary String, we have to access the utf8 property of the input to get a [UInt8] that we can iterate over.

  • We need to concatenate "" with $0 (the implicit closure parameter, aka the input) to help the type checker figure out that $0 is a String.

\$\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.

\$\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 !

\$\endgroup\$
2
  • \$\begingroup\$ Can reduce to 96 by not assigning input() to the variable s. Try it online! \$\endgroup\$
    – ElPedro
    Mar 15, 2018 at 13:11
  • \$\begingroup\$ Good one @ElPedro I will edit! \$\endgroup\$ Mar 15, 2018 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`~'
\$\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!

\$\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!

\$\endgroup\$
1
1
\$\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?")))

    )) 
\$\endgroup\$
1
\$\begingroup\$

05AB1E (legacy), 11 bytes

„AaS¡εNFš]J

Try it online!

\$\endgroup\$
1
\$\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
\$\endgroup\$
2
  • 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\$ Oct 30, 2020 at 0:43
  • 1
    \$\begingroup\$ @cairdcoinheringaahing whitespace is mandatory around ? and : in the conditional operator. I removed whitespace where I could. \$\endgroup\$
    – binarycat
    Oct 30, 2020 at 2:33
1
\$\begingroup\$

Julia 1.0, 73 71 bytes

f(s,b=0)=[c∈"aA" ? b=32-b : print(c+isletter(c)sign('_'-c)b) for c=s]

Try it online!

Stolen and improved from Simeon Schaub's great answer

-2 bytes thanks to Czylabson Asa

\$\endgroup\$
1
  • 1
    \$\begingroup\$ a slight improvement: 71 bytes \$\endgroup\$ Jun 29, 2022 at 13:35
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.
\$\endgroup\$
0
\$\begingroup\$

Pyth, 19 bytes

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

Try it here.

Saved one byte thanks to mnemonic.

\$\endgroup\$
0
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.

\$\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)))
\$\endgroup\$
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.
\$\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!

\$\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}
\$\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
\$\endgroup\$
1
  • \$\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, 2018 at 23:05
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
\$\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
\$\endgroup\$
0
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...

\$\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.

\$\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

\$\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))])
\$\endgroup\$
4
  • 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, 2019 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, 2019 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, 2019 at 14:41
  • 1
    \$\begingroup\$ ... and there are two spaces between for i,j in and enumerate( \$\endgroup\$ Aug 8, 2019 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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