## No A, just CAPS LOCK

205

13

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.

113Welcome to the site! This is a nice first challenge, and unfortunately very relatable for me and my fT FINGERS. – James – 2018-03-14T18:29:23.957

What characters will be in the input ? a-zA-Z? – Rod – 2018-03-14T18:42:32.610

5suggested test case : teSTateSTateSTateST – Rod – 2018-03-14T18:44:19.673

@Rod Look at the examples. Printable ASCII seems to be included. – mbomb007 – 2018-03-14T18:44:35.260

@Rod -> teSTTEstteSTTEst. – mbomb007 – 2018-03-14T18:45:18.937

@Rod All characters except 'a' or 'A' are allowed in the output. Non-letters do not get changed. – Broadwell – 2018-03-14T18:50:22.867

1@Broadwell He said "input", not "output" – mbomb007 – 2018-03-14T18:56:48.113

2hey so in the future I would recommend using sandbox :P but very good challenge – Christopher – 2018-03-14T19:00:28.073

3

@Christopher is referring to the Sandbox, which is where users typically post questions to ask for improvements.

– Giuseppe – 2018-03-14T19:05:16.153

92If only the enter key also had a notch in it so this wouldn' – 12Me21 – 2018-03-14T19:33:18.153

78t happen....... – 12Me21 – 2018-03-14T19:33:28.233

1TIL that @DJMcMayhem was trying to create the nick DJMACMayhem... – Olivier Dulac – 2018-03-15T17:01:37.973

24Literally joined this site to upvote "Without the notch, no one can hear you scream" – lucasvw – 2018-03-15T21:10:11.917

Is the sixth example correct? – Andrea Lazzarotto – 2018-03-16T17:40:48.540

3Why is the title of this question not “No A, just cPS LOCK”? – Janus Bahs Jacquet – 2018-03-16T17:59:29.040

1Wouldn't it be "No , JUST Cps lock"? – 12Me21 – 2018-03-16T20:54:51.550

5I LSO WISH THt my keyboRD Hd a bigger bCKSPce kwt==et=y – Nonny Moose – 2018-03-16T20:58:15.287

@12Me21 I was allowing for not missing the A key when also holding down the shift key at the same time, since shift + caps lock is actually more difficult than shift + A. Also that would make the title completely illegible. But yes, if we went for the purely programmatic approach, it would. – Janus Bahs Jacquet – 2018-03-18T09:58:59.923

Related – Shaggy – 2018-03-19T01:20:54.093

Test case: correct horse bTTERY STple – MilkyWay90 – 2019-06-24T15:46:22.520

120

# AutoHotKey, 7 bytes

a::vk14


// Is this valid? This really do what OP want -- replace a by CapsLock (vk14).

Run this program, and type the input from keyboard..

4"Is this valid?" OP did not specify input or output constraints so I´d consider this valid. – Nefrin – 2018-03-15T13:22:10.347

6Don't see too many ahk answers! – HaveSpacesuit – 2018-03-15T13:57:52.363

1"my code runs everywhere" – sudo rm -rf slash – 2018-03-15T15:02:20.060

1I would cLL THIS Vlid! – gsquaredxc – 2018-03-16T00:37:53.547

58ThT'S GREt but how do I disBLE IT? – RobbG – 2018-03-16T13:52:35.650

71@RobbG just type "killLL utohotkey" ... oh wIT – Nefrin – 2018-03-16T14:04:33.133

1@RobbG You could copy/pSTE THE in the title. – jpmc26 – 2018-03-20T02:19:39.270

33

# V, 9 bytes

ò/ãa
xg~$ Try it online! Hexdump: 00000000: f22f e361 0a78 677e 24 ./.a.xg~$


Explanation:

ò       " Recursively:
/ãa    "   Move forward to the next 'a' (upper or lowercase)
"   This will break the loop when there are no more 'a's
x       "   Delete the 'a'
g~$" Toggle the case of every character after the cursor's position.  22 # Vim, 16 bytes qq/\ca xg~$@qq@q


Assumes the input is on a single line

## Explanation

qq            Start a loop
/\ca␊         Find the first occurence of an a, end the loop if there are none left
xg~$Remove it and invert the case of the rest of the file @qq@q End the loop  Is this case insensitive finding of 'a'? – Gnudiff – 2018-03-16T21:06:49.943 @Gnudiff \c anywhere in a regex-search enables case-insensitivity – Herman L – 2018-03-16T21:14:24.593 Do you need to set a specific flag for g~$ to work? Because for me it only inverts case until the end of the line, not the whole file, so this doesn't really work for multiline files for me. – Cubic – 2018-03-19T15:34:58.143

1@Cubic As I wrote in the answer, it "assumes the input is on a single line" – Herman L – 2018-03-19T15:58:25.717

@Cubic If you wanted it to go the end of the file and support inputs on multiple lines, you could do g~vG or vG~. – James – 2018-03-19T17:15:01.247

@DJMcMayhem I think using 'n' instead of '$' would work also? – nmjcman101 – 2018-03-19T21:28:09.073 15 # C, 72 bytes Thanks to @Ton Hospel for helping to save 16 bytes! t,c;f(char*s){for(t=0;c=*s++;6305%c?putchar(isalpha(c)?c^t:c):(t^=32));}  Try it online! 2You can swap the case of letters using a xor with 32 – Ton Hospel – 2018-03-14T19:19:46.733 You can probably save even more by having t be 0/32 instead of even/odd (xor t with 32 for each a) and then xor letters directly with t – Ton Hospel – 2018-03-14T20:14:31.497 2Nice way to detect a's – Ton Hospel – 2018-03-14T20:17:15.370 And why initialize t ? It starts as 0 anyways :-) (though you will have to set it back to 0 after each f call in the footer) – Ton Hospel – 2018-03-14T21:51:17.637 1 @TonHospel Functions have to be reusable, and I don't think it counts as reusable if you need external code to make it usable again after each call. – Steadybox – 2018-03-15T10:49:21.730 16305%c is 0 if c is 13. – Rosie F – 2018-03-16T11:55:12.340 12 # Retina, 3321 17 bytes i(TvlLLla.* a  Try it online Explanation: i( i is for case-insensitive, the paren makes it modify both stages Tv Transliteration, with simple overlaps (v) - 1 match at every start pos lLLl Replace lowercase with uppercase, and vice versa a.* Every 'a' will match, overlapping to the end of the string This swaps the case on all letters after each 'a' a Replace all 'a's with nothing  -12 bytes thanks to Martin -4 bytes thanks to Leo Amazingly this is almost as short as the current Pyth solutions – Ton Hospel – 2018-03-14T19:11:39.620 1I think iTaAlL__Lla[^a]*a? also works for 21 bytes. – Neil – 2018-03-14T20:29:06.253 4 bytes shorter using overlapping matches – Leo – 2018-03-14T21:37:15.243 I'm interested in how this works if you have time to add the explanation. Thanks! – seshoumara – 2018-03-15T07:41:04.417 11 # Husk, 11 bytes Γ·§?m\:€"Aa  Try it online! ## Explanation I'm using the somewhat obscure overloading of Γ called listNF, which constructs recursive functions that operate on lists. It corresponds to the following Haskell pattern: listNF f = g where g (x : xs) = f g x xs g [] = []  The idea is that listNF takes a helper function f and returns a new function g, which takes a list. The function f takes a function, which will always be g, and the head x and tail xs of the list, and does something with them. In our application, f calls g recursively on xs. The program is interpreted like this: Γ (· (§ (?m\) : (€"Aa"))) Γ ( ) Create a function g that takes a list (x:xs) and applies a function on x and xs. · ( ) Compose g with second argument of function in parentheses. Instead of x and xs, the function is called on x and the result of a recursive call of g on xs. (€"Aa") Check if x is 'A' or 'a'. (?m\) If it is, then swap the case of every char in g(xs). § : Otherwise, prepend x to g(xs).  3Wow, good thing I refreshed before I posted my 12 byte solution: Ḟ·+m\ṁx'Ax'a. Could we get an explanation? I can't find any information on what Γ does exactly and this seems like a good chance to learn. – Sophia Lechner – 2018-03-15T00:02:24.023 1@SophiaLechner Done. This version of Γ is a bit hard to explain, I hope you can make sense of it. – Zgarb – 2018-03-15T08:16:56.773 Wow this is slow. Is it just TIO? – FrownyFrog – 2018-03-15T13:00:23.287 1@FrownyFrog It's Husk. Type inference of programs containing Γ seems to be slow in general. If you're not familiar with Husk, a program is interpreted by looping through all possible structures of the program (essentially the possible placements of parentheses) and all overloadings of each built-in, and choosing the first one where the result is well-typed. The interpreter is smart enough to reject some possibilities early, but it seems that the recursive version of Γ can mess with this step and force it to loop through a lot of choices. – Zgarb – 2018-03-15T13:34:00.870 @SophiaLechner I wrote a tip that explains Γ in some detail. – Zgarb – 2018-03-15T14:42:44.827 7 # JavaScript (ES6), 938884 82 bytes (saved 5 bytes thanks to @Shaggy, 4 bytes thanks to @user81655, and 2 bytes thanks to @l4m2.) a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[to${c<{}?'Low':'Upp'}erCase]())


Test cases:

let f=

a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[to${c<{}?'Low':'Upp'}erCase]()) console.log(f("The quick brown fox jumps over the lazy dog.")); console.log(f("Compilation finished successfully.")); console.log(f("What happens when the CapsLock key on your keyboard doesn't have a notch in it?")); console.log(f("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.")); console.log(f("aAaaaaAaaaAAaAa")); console.log(f("CapsLock locks cAPSlOCK")); console.log(f("wHAT IF cAPSlOCK IS ALREADY ON?")); 1['to${c<'a'?'Low':'Upp'}erCase'] should save you a few bytes, replacing single quotes with backticks. – Shaggy – 2018-03-15T00:13:06.960

Sure does, @Shaggy. Thanks! – Rick Hitchcock – 2018-03-15T15:51:40.360

Using ^1 to have u be the parity can let you initialise it shorter: s=>s.replace(u=/./g,c=>/a/i.test(c)?(u^=1,''):+u?c[to${c<'a'?'Low':'Upp'}erCase]():c) – user81655 – 2018-03-18T07:45:19.653 Also here's another tricky way to test for the letter a which is shorter: a=>a.replace(A=/./g,c=>c in{a,A}?(A^=1,''):+A?c[to${c<'a'?'Low':'Upp'}erCase]():c) – user81655 – 2018-03-18T07:53:03.500

Brilliant, @user81655, especially using the in operator like that. Always more to learn! – Rick Hitchcock – 2018-03-18T10:45:12.173

Use {} as "[object Object]" to distingish upper and lower – l4m2 – 2018-04-09T11:18:52.877

Very nice, @l4m2, thanks! – Rick Hitchcock – 2018-04-09T17:47:26.423

@RickHitchcock does a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[to${c<{}?'Low':'Upp'}erCase]()) work? – l4m2 – 2018-04-09T17:50:58.803 Ahh, that's what you meant by Use {}. Sorry, yes, that's perfect, thanks again. – Rick Hitchcock – 2018-04-09T18:12:53.650 6 # Perl 5-p, 3130 29 bytes -1 byte thanks to @nwellnhof -1 byte thanks to @ikegami #!/usr/bin/perl -p s/a([^a]*)a?/$1^uc$1^lc$1/egi


Try it online!

Why not simply s/a(.*?)(a|$)/uc$1/egi (22 bytes)? – nwellnhof – 2018-03-16T13:59:51.633

@nwellnhof Because the capslock when active toggles the case, it doesn't just uppercase – Ton Hospel – 2018-03-16T15:18:06.987

1Ah, I see. Then s/a(.*?)(a|$)/$1^uc$1^lc$1/egi is one byte shorter. – nwellnhof – 2018-03-16T18:09:09.847

@nwellnhof Thanks, that is very neat – Ton Hospel – 2018-03-16T20:51:27.040

a([^a]*)a? is shorter than a(.*?)(a|$) – ikegami – 2018-03-18T08:47:52.173 6 # R, 92 bytes cat([<-(v<-el(strsplit(scan(,""),"a|A")),w<-c(F,T),chartr("a-zA-Z","A-Za-z",v)[w]),sep="")  Thank @Giuseppe for fixing the answer. Explanation # Write cat( # Replace and return, this is the function that powers # the R store at index operations, a[i]<-b [<-( # First arg - what to replace = extract first list element # of a string input after splitting at a or A v<-el(strsplit(scan(,""),"a|A")), # Second arg - index to replace = abuse vector recycling # to create infinite F, T, F, T, F, etc series w<-c(F,T), # Third arg - replacement values = replace with case toggled letters chartr("a-zA-Z","A-Za-z",v)[w]), # Write without separation sep="")  Try it online! Perhaps I didn't make it clear, but this answer does not reverse capitalization when CapsLock is enabled (it only performs toupper), which is a requirement. – Broadwell – 2018-03-14T21:19:24.673 2ooohhhhhhh that's very clever with the c(F,T), although @Broadwell is right; looks like it'll be a chartr("a-zA-Z","A-Za-z",v)[w] rather than toupper – Giuseppe – 2018-03-14T21:22:39.963 @Giuseppe Thanks – Vlo – 2018-03-14T21:35:25.637 6 # Java 8, 119108 98 bytes s->{int f=0,t;for(int c:s)if((t=c&95)==65)f^=1;else System.out.printf("%c",f<1|t<66|t>90?c:c^32);}  -11 bytes thanks to @OlivierGrégoire. -10 bytes thanks to @Nevay. Explanation: Try it online. s->{ // Method with char-array parameter and no return-type int f=0,t; // Flag-integer, starting at 0 for(int c:s) // Loop over the characters of the input as integers if((t=c&95)==65) // If the current character is an 'A' or 'a': f^=1; // Toggle the flag (0→1 or 1→0) else // Else: System.out.printf("%c", // Print integer as character f<1| // If the flag-integer is 0, t<66|t>90? // or the current character isn't a letter: c // Simply output the character as is : // Else (the flag it 1 and it's a letter) c^32);} // Print it with its case reversed  1Damn imperatives... they forbade me to post my answer before yours... Anyways, here's my answer, 11 bytes shorter: s->{int z=0,d;for(int c:s)if((d=c&95)==65)z^=1;else System.out.printf("%c",z<1|d<66|d>90?c:c<91?c|32:c&95);} – Olivier Grégoire – 2018-03-15T10:51:37.570 @OlivierGrégoire Nice answer! And what do you mean by forbade me to post? Is your work-network that strict? – Kevin Cruijssen – 2018-03-15T11:16:26.653 My answer was ready for a while: I was just polishing the test cases before posting but then suddenly endless meetings happened. – Olivier Grégoire – 2018-03-15T11:19:15.073 @OlivierGrégoire Ah of course.. The meetings that always come at the wrong time.. I know the feeling sometimes. ;) – Kevin Cruijssen – 2018-03-15T11:21:05.540 No, it's just that your answer was so similar to mine that it wouldn't have been correct to post mine ;) – Olivier Grégoire – 2018-03-15T11:22:55.190 @OlivierGrégoire If you want I can delete mine and you can post it as yours. You've got my upvote if you do. :) – Kevin Cruijssen – 2018-03-15T12:59:04.873 1No, it's ok, I only have to blame myself for not being quick enough before the meetings ;-) But thank you for suggesting this! – Olivier Grégoire – 2018-03-15T13:23:39.207 298 bytes: s->{int f=0,t;for(int c:s)if((t=c&95)==65)f^=1;else System.out.printf("%c",f<1|t<66|t>90?c:c^32);} – Nevay – 2018-03-17T17:01:00.903 6 # C, 167168158 131 bytes Thanks for @Martin Ender for the code review: I've switched the stream processing for string processing to help with reusability. Also many thanks to @RiaD and @ceilingcat for their suggestions. c,d;(*t[][2])()={{isupper,tolower},{islower,toupper}};f(char*s){for(d=1;c=*s++;)t[0][1](c)==97?d=!d:putchar(t[!t[d][0](c)][1](c));}  Try it online! # How does it work? /* int c is the input character, int d is the Caps Lock flag (1=off, 0=on) starting as "Off". */ int c, d; /* array of comparison functions and transformation functions for each state */ (*t[][2])() = {{isupper, tolower}, {islower, toupper}}; f(char *s) { /* Loop if we haven't hit the terminator */ for(d = 1; c = *s++;) t[0][1](c) == 97 ? /* If tolower(c)=='a' then flip the Caps Lock state */ d=!d: /* Otherwise, convert character according to the following table: Character case Caps Lock UPPER LOWER ON tolower() toupper() OFF toupper() tolower() */ putchar(t[!t[d][0](c)][1](c)); } }  # Notes • s[][] is where the magic happens: [][0] is the comparison function and [][1] is the related transformation function for each state. • ! is applied to the comparison function to force it into the range [0,1]. Welcome to PPCG! Unfortunately, you can't rely on the initialisation of d like this because it means that your function is not reusable. A simple d=0; should fix it. – Martin Ender – 2018-03-16T10:01:12.883 I wasn't sure if reusability or maintaining state was more important in this case. If reusability is more important, I would move the variable declarations inside the function so the beginning would read void f(){int c,d=0;[...]. In any case, the stream dies, so an edit is in order! – ErikF – 2018-03-16T11:05:06.710 do you need s in your while loop? It can't became NULL unless you called with f(NULL) – RiaD – 2018-03-16T14:42:41.660 d=!d for flipping – RiaD – 2018-03-16T14:43:30.913 !! will be ! if you flip order of t, and start d with 1 – RiaD – 2018-03-16T14:54:20.293 you may also just remove first 2 – RiaD – 2018-03-16T17:21:20.857 Suggest 1[*t] instead of t[0][1] – ceilingcat – 2018-12-30T17:58:55.003 6 # PowerShell Core, 105 bytes "$args"|% t*y|%{if($_-in97,65){$c=!$c}else{Write-Host -n($_,("$_"|%("*per","*wer")[$_-in65..90]))[!!$c]}}  Try it online! What with no real ternary operator and no default alias for printing to screen, it's not that short. • % t*y expands to | ForEach-Object -Method ToCharArray equiv. of "$args".ToCharArray()
• Write-Host -n is for the parameter -NoNewLine
• "$_" turns the [char] type back to [string] (chars have no upper/lower case in .Net) • |% *per does the same method call shortcut as earlier, but for .ToUpper(), same with .ToLower() • ($a,$b)[boolean test] abused as fake-ternary operator • !!$c force-casts to [bool] here it starts undefined $null so it gets forced it into existence as "caps lock:$false".

1That |% t*y is a neat trick I'll need to remember. Shorter than [char[]], which I use a lot. I'd almost say that should go onto the Tips thread. – AdmBorkBork – 2018-03-19T13:10:14.480

94 bytes: -join($args|% t*y|%{if($_-eq'a'){$c=!$c}else{(("$_"|%("*per","*wer")[$_-in65..90]),$_)[!$c]}}). thanks for a |% *ethod operator! – mazzy – 2018-07-08T11:55:59.810

5

# Python, 63 bytes

f=lambda s:s and[s[0]+f(s[1:]),f(s[1:]).swapcase()][s[0]in"aA"]


Another Python solution, works in Python 2 and 3. Takes a very long time for all but small inputs.

5

# 6502 machine code routine (C64), 51 bytes

A0 00 84 FE B1 FC F0 2A C9 41 F0 06 90 1A C9 C1 D0 08 A9 80 45 FE 85 FE B0 11
B0 06 C9 5B B0 08 90 04 C9 DB B0 02 45 FE 20 16 E7 C8 D0 D6 E6 FD D0 D2 60


Expects a pointer to a 0-terminated input string in $fc/$fd, outputs to the screen.

### Commented disassembly

 .caps:
A0 00       LDY #$00 84 FE STY$FE             ; init capslock state
.loop:
B1 FC       LDA ($FC),Y ; next char from string F0 2A BEQ .done ; NUL -> we're done C9 41 CMP #$41            ; compare to 'a'
F0 06       BEQ .isa            ; if equal, toggle capslock
90 1A       BCC .out            ; if smaller, direct output
C9 C1       CMP #$C1 ; compare to 'A' D0 08 BNE .ctog ; if not equal, check for letter .isa: A9 80 LDA #$80            ; toggle bit 7 in caps lock state
45 FE       EOR $FE 85 FE STA$FE
B0 11       BCS .next           ; and go on
.ctog:
B0 06       BCS .cZ             ; if char larger 'A', check for 'Z'
C9 5B       CMP #$5B ; compare with 'z'+1 B0 08 BCS .out ; larger or equal -> direct output 90 04 BCC .tog ; smaller -> apply capslock .cZ: C9 DB CMP #$DB            ; compare with 'Z'+1
B0 02       BCS .out            ; larger or equal -> direct output
.tog:
45 FE       EOR $FE ; toggle bit from capslock state .out: 20 16 E7 JSR$E716           ; output char
.next:
C8          INY                 ; and loop to next char
D0 D6       BNE .loop
E6 FD       INC $FD D0 D2 BNE .loop .done: 60 RTS  ### Example assembler program using the routine: Online demo Code in ca65 syntax: .import caps ; link with routine above .segment "BHDR" ; BASIC header .word$0801           ; load address
.word   $080b ; pointer next BASIC line .word 2018 ; line number .byte$9e             ; BASIC token "SYS"
.byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
string:         .res    $800 .data prompt: .byte$d, "input> ", $0 .code lda #$17            ; set upper/lower mode
sta     $d018 lda #<prompt ; display prompt ldy #>prompt jsr$ab1e

lda     #<string        ; read string into buffer
sta     $fc lda #>string sta$fd

lda     #>string        ; call our caps routine on buffer
sta     $fd jmp caps ; read a line of input from keyboard, terminate it with 0 ; expects pointer to input buffer in$fc/$fd ; NO protection agains buffer overflows !!! .proc readline ldy #$0
sty     $cc ; enable cursor blinking sty$fe             ; temporary for loop variable
lda     $fd sta$2              ; initial page of string buffer
getkey:         jsr     $f142 ; get character from keyboard beq getkey sta$fb             ; save to temporary
and     #$7f cmp #$20            ; check for control character
bcs     prepout         ; no -> to normal flow
cmp     #$d ; was it enter/return? beq prepout ; -> normal flow cmp #$14            ; was it backspace/delete?
bne     getkey          ; if not, get next char
lda     $fe ; check current index bne prepout ; not zero -> ok lda$2              ; otherwise check if we're in the
cmp     $fd ; first page of the buffer beq getkey ; if yes, can't use backspace prepout: ldx$cf             ; check cursor phase
beq     output          ; invisible -> to output
sei                     ; no interrupts
ldy     $d3 ; get current screen column lda ($d1),y         ; and clear
and     #$7f ; cursor in sta ($d1),y         ;   current row
cli                     ; enable interrupts
output:         lda     $fb ; load character jsr$e716           ;   and output
ldx     $cf ; check cursor phase beq store ; invisible -> to store sei ; no interrupts ldy$d3             ; get current screen column
lda     ($d1),y ; and show ora #$80            ;   cursor in
sta     ($d1),y ; current row cli ; enable interrupts lda$fb             ; load character
store:          cmp     #$14 ; was it backspace/delete? beq backspace ; to backspace handling code ldy$fe             ; load buffer index
sta     ($fc),y ; store character in buffer cmp #$d             ; was it enter/return?
beq     done            ; then we're done.
sty     $fe bne getkey ; not zero -> ok inc$fd             ; otherwise advance buffer page
bne     getkey
done:           lda     #$0 ; terminate string in buffer with zero ldy$fe             ; get buffer index
iny
bne     termidxok       ; and advance ...
inc     $fd termidxok: sta ($fc),y         ; store terminator in buffer
inc     $cc ; disable cursor blinking rts ; return backspace: ldy$fe             ; load buffer index
bne     bsidxok         ; if zero
dec     $fd ; decrement current page bsidxok: dey ; decrement buffer index sty$fe
bcs     getkey          ; and get next key
.endproc


I just have to say I admire you went to the effort to write in assembly. I don’t think this has much to do with the fact I used to really enjoy asm but maybe having the experience makes me more aware of what it entails. Experience or ease is besides the point to me. It brightens my day just a bit to see such enthusiasm too. – Pryftan – 2018-03-18T21:23:58.290

@Pryftan thanks :) It's just a nice way to keep in practice, I'm working on some game and recently also demo code for this nice old machine :) – Felix Palmen – 2018-03-19T08:20:10.763

Well it's great to see! Keep it up; I remember enjoying asm but I don't think I'd enjoy it so much nowadays (unless maybe I had an old machine like you do, that is but possibly not even then) - C is my favourite all time and it's what I primarily use. Anyway, won't let this evolve into chat - just wanted to say I appreciated the answer! – Pryftan – 2018-03-19T20:56:35.967

4

# Jelly, 14 bytes

Œu=”Aœp⁸ŒsJḤ$¦  Try it online! Full program. Explanation: Œu=”Aœp⁸ŒsJḤ$¦ Arguments: x
Œu             Uppercase x
=”A          ^ Equals 'A' (vectorizes)
œp⁸       ^ Partition ⁸ [⁸=x]
¦ Apply link A, keep results at specific indices B
Œs     A: Swap case
$B: Form a >=2-link monadic chain JḤ Arguments: y J Get list indices ([1, length(list)]) of y Ḥ Double (vectorizes) ^ This way, we only "apply" link A to even indices, so every second element, starting from the secondd one.  Explanation of the code? – SK19 – 2018-03-16T22:00:40.027 1@SK19 Added an explanation. – Erik the Outgolfer – 2018-03-19T10:07:51.550 4 # Haskell, 92 bytes import Data.Char g x|x<'['=toLower x|1>0=toUpper x f(a:b)|elem a"aA"=f$g<$>b|1>0=a:f b f x=x  Try it online! ## Explanation First we declare g to be the function that maps lowercase to upper case and uppercase to lowercase. This is actually the majority of our bytecount. Then we define the function f. If the input to f is of the form a:b we do f(a:b) |elem a"aA"=f$g<$>b |1>0=a:f b  a and A match the first pattern and thus we apply f to the input with it's case inverted. Otherwise we move a out front and apply f to b. 4 # 05AB1E, 12 bytes õ?„AaS¡Dvć?š  Try it online! Explanation õ? # print an empty string (to account for the special case of only A's) „AaS¡ # split on occurrences of "A" or "a" D # duplicate v # for each element in the top copy ć? # extract and print the head of the other copy š # switch the case of the rest of the other copy  4 # PHP101 99 bytes for($s=$argn;$i<strlen($s);$i++)lcfirst($s[$i])==a?$s=strtolower($s)^strtoupper($s)^$s:print$s[$i];


Run like this:

echo '[the input]' | php -nR '[the code]'


Ungolfed:

for ($s =$argn; $i < strlen($s); $i++) { if (lcfirst($s[$i]) == 'a') {$s = strtolower($s) ^ strtoupper($s) ^ $s; // Flip the whole string's case. } else { print$s[$i]; // Print the current letter. } }  This just loops through the string with a for loop, and on each iteration it checks if the current letter is a, if so, then flip the case of the whole string (method from here), and if not, then print the current letter. 1The convention for code golf is that all code must be included. That means you have to take input as function parameter and actually declare a function (via the function keyword in php) or have a complete script (e.g. using $argn, $argv, $_GET). So at the moment this is not a correct submission. Return must be echoed or returned (only allowed for functions ofc). – Christoph – 2018-03-15T12:10:32.873

1Thanks for that @Christoph, I'm kind of new to golfing :). I've updated my answer now, just let me know if there's anything else that's wrong. – Ethan – 2018-03-15T20:14:33.897

@Christoph Wow! 75! Very nice! You have my +1 :) – Ethan – 2018-03-16T16:07:07.897

4

# Ruby, 42 41 bytes

->s{s.sub!(/a(.*)/i){$1.swapcase}?redo:s}  Try it online! A lambda accepting a string, mutating the string in place, and returning it. The trick here is that sub returns the string (a truthy value) if a substitution was made, and returns nil otherwise. The existence of swapcase is pretty handy, too. -1 byte: Replace boolean logic with ternary operator, thanks to Asone Tuhid ->s{ s.sub!(/a(.*)/i){ # Replace "a" followed by anything with$1.swapcase         #   the case-swapped capture group
} ? redo              # If a match was found, restart the block
: s                 # Otherwise, return the modified string
}


save 1 byte. The link was too long if I included all the test cases. – Asone Tuhid – 2018-03-16T06:17:40.600

@AsoneTuhid Thanks... One of these days I'll remember to use the ternary operator straight away, so you won't have to remind me. – benj2240 – 2018-03-16T15:01:22.933

4

# Wolfram Language (Mathematica), 70 bytes

#//.{x___,"a"|"A",y___}:>Join[{x},ToUpperCase@#+ToLowerCase@#-#&@{y}]&


Try it online!

Takes input and output as a list of characters. For convenience I've added code in the footer to convert this from and back to a string.

# How it works

The #//.{x___,"a"|"A",y___}:>Join[{x},...{y}]& part is standard: we find the first A (uppercase or lowercase), reverse case of that comes after the A, and repeat until there are no more A's to be found.

The interesting part is how we reverse case: the function ToUpperCase@# + ToLowerCase@# - #&. We add together the upper-cased version of the input and the lower-cased version of the input, then subtract the actual input. For example, given the list {"I","n","P","u","T"} this computes

{"I","N","P","U","T"}+{"i","n","p","u","t"}-{"I","n","P","u","T"}


{"I"+"i"-"I","N"+"n"-"n","P"+"p"-"P","U"+"u"-"u","T"+"t"-"T"}


and although Mathematica doesn't have any particular way of adding two strings, it's smart enough to simplify a+b-a to b for any values of a and b, including string values, so this simplifies to {"i","N","p","U","t"}.

4

# MATL, 23 20 bytes

'a A'Yb&Ybt2L)Yo2L(g


Try it online!

### Explanation:

'a A'Yb   % form a cell array containing {'a', 'A'}
&Yb       % split input into substrings, with either of those ('a' or 'A') as delimiters
t2L)      % extract out the even positioned cells from that result
Yo        % switch the case of those substrings
2L(       % place the result back in even positioned cells of the original cell array
g         % convert cell array to matrix, concatenating all substrings in the process
% implicit output


"H@'aA'm?~XHx}@w~?Yo]&h

Other methods I tried:

0w"@t'aA'm?x~}y?Yo]w]]xv!
t'aA'mXHYsot&y*XzcYowf([]H(
t'aA'mXHYsoy3Y2m*32*Z~c[]H(


3

# SNOBOL4 (CSNOBOL4), 141 92 bytes

	I =INPUT
S	I ANY("Aa") REM . R =REPLACE(R,&LCASE &UCASE,&UCASE &LCASE) :S(S)
OUTPUT =I
END


Try it online!

Assumes a single line of input.

A whopping 49 bytes saved by @ninjalj!

Line S does all the work, explained below:

I                    # in the subject string I match the following PATTERN:
ANY("Aa")           # match A or a and
REM . R             # match the remainder of I, assigning this to R
=REPLACE(           # replace the PATTERN above with
R, ...)    # R with swapped cases.
:S(S)             # and if there was a match, goto S, else goto next line 

This gives the wrong answer (as you stated in your comment, case is swapped when CapsLock is on) – mbomb007 – 2018-03-14T18:34:36.687

I've edited the post to require case-swapping (rather than simply uppercase) when CapsLock is enabled because I never realized that my machine does this. – Broadwell – 2018-03-14T18:35:52.927

@mbomb007 ah, I hadn't realized OP had changed it; I'm editing for an explanation now so I'll include that in the explanation. – Giuseppe – 2018-03-14T18:35:57.230

I =INPUT;S I ANY("Aa") REM . R =REPLACE(R,&LCASE &UCASE,&UCASE &LCASE) :S(S); OUTPUT =I;END – ninjalj – 2018-03-16T01:02:02.957

@ninjalj are you also a SNOBOL golfer or am I just terrible at golfing it?? – Giuseppe – 2018-03-16T13:35:25.717

@Giuseppe: I used to golf occasionally in SNOBOL at golf.shinh.org – ninjalj – 2018-03-16T19:27:23.190

3

# Husk, 15 bytes

ω(F·+otm\↕·≠_'a


Try it online!

### Explanation

ω(F·+(tm\)↕·≠_'a) -- example input: "Bar, baz and Foo."
ω(              ) -- apply the following, until fixpoint is reached:
↕       -- | split string with predicate
· _    -- | | the lower-cased character
≠ 'a  -- | | is not 'a'
-- | : ("B","ar, baz and Foo.")
F               -- | apply the following to the tuple
+             -- | | join the elements with..
· (   )        -- | | ..the second element: "ar, baz and Foo."
m\         -- | | | swap case: "AR, BAZ AND fOO."
t           -- | | | tail: "R, BAZ AND fOO."
-- | : "BR, BAZ AND fOO."
-- : "BR, Bz ND fOO."


3

# Stax, 12 bytes

ìo'½║â↨╪U?5


Run and debug it online

It splits on a regex, and then alternately toggles case. Here's the same program, unpacked, ungolfed, and commented.

"a|A"|s split on regex /a|A/
rE  reverse and explode array to stack
W   repeat forever...
p   print top of stack with no newline
:~p print top of stack, case inverted, with no newline


Run this one

I somehow cannot relate your explanation to your code. – SK19 – 2018-03-16T21:59:14.943

Try stepping through the commented one, and watching the internal state of the interpreter. Does that help? – recursive – 2018-03-16T22:29:54.607

1@SK19: Oh, I think I see the problem. I didn't mention that stax programs have two representations. Ascii and packed. There's a lossless conversion between the two. Ascii is easy to type, but wasteful for golf, since there are only 95 symbols. The golfed program is packed, so it looks different, but it's the same program. – recursive – 2018-03-16T23:45:17.110

3

# Japt v2.0a0, 16 bytes

e/a.*/i_År\l_c^H


Try it

## Explanation

e                   :Recursively replace
/a.*/i             :RegEx /a.*/gi
_            :Pass each match through a function
Å           :  Slice off the first character
r          :  Replace
\l        :  RegEx /[A-Za-z]/g
_       :  Pass each match though a function
c^     :    Bitwise XOR the character code
H    :    With 32


3

# Rust, 330 bytes

fn main(){let mut i=String::new();std::io::stdin().read_line(&mut i);let mut o=vec![];let mut c=false;for l in i.trim().as_bytes(){if*l==65||*l==97{c=!c;}else if c{if l.is_ascii_uppercase(){o.push((*l).to_ascii_lowercase());}else{o.push((*l).to_ascii_uppercase());}}else{o.push(*l);}}println!("{}",String::from_utf8(o).unwrap());}


Ungolfed

fn main() {
let mut input = String::new();
let mut output_chars = vec![];
let mut capslock = false;
for letter in input.trim().as_bytes() {
if *letter == 65 || *letter == 97 {
capslock = !capslock;
} else if capslock {
if letter.is_ascii_uppercase() {
output_chars.push((*letter).to_ascii_lowercase());
} else {
output_chars.push((*letter).to_ascii_uppercase());
}
} else {
output_chars.push(*letter);
}
}
println!("{}", String::from_utf8(output_chars).unwrap());
}


Since this uses bytes instead of chars in the loop, 65 and 97 are the byte values for 'A' and 'a'.

I'm new to Rust, so this might be golfable further.

3Welcome to PPCG! – Giuseppe – 2018-03-15T12:09:49.960

3

foreach(spliti(a,$argn)as$b)echo$a++&1?strtoupper($b)^strtolower($b)^$b:$b;  Split into substrings by A (case insensitive) then toogle every second case. Old version for(;a&$c=$argn[$i++];)trim($c,aA)?print($c^chr($f*ctype_alpha($c))):$f^=32;  walks over the string and toogles a flag if the current char is a or A else the char gets toogled depending on the flag and echoed. 3 # Fortran (GFortran), 307 bytes CHARACTER(999)F,G G=' ' READ(*,'(A)')F N=1 M=1 DO I=1,999 IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN M=-M ELSEIF(M==1)THEN G(N:N)=F(I:I) N=N+1 ELSE J=IACHAR(F(I:I)) SELECTCASE(J) CASE(65:90) G(N:N)=ACHAR(J+32) CASE(97:122) G(N:N)=ACHAR(J-32) CASE DEFAULT G(N:N)=F(I:I) ENDSELECT N=N+1 ENDIF ENDDO PRINT*,TRIM(G) END  Try it online! Since Fortran has not "advanced" tools for dealing with strings, I came up with this little monster. Indented and commented: CHARACTER(999)F,G !Define input and output strings (up to 999 characters) G=' ' !Fill output with spaces READ(*,'(A)')F !Take input N=1 !Represent the position to be written in output string M=1 !M=-1: Change case; M=1: Do not change case DO I=1,999 IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN !If the character is A... M=-M !Ah-ha - you pressed cPS-LOCK! ELSEIF(M==1)THEN !Case the character is not A, and do not need to change case... G(N:N)=F(I:I) !...only copy the character N=N+1 ELSE !Otherwise... J=IACHAR(F(I:I)) !...get ascii of current character SELECTCASE(J) CASE(65:90) !If is upper case, G(N:N)=ACHAR(J+32) !now is lower case CASE(97:122) !If is lower case, G(N:N)=ACHAR(J-32) !now is upper case CASE DEFAULT !If do not belong to alphabet, G(N:N)=F(I:I) !simply copy the character ENDSELECT N=N+1 ENDIF ENDDO PRINT*,TRIM(G) !Trim out trailing spaces END !That's all folks!  3 ## 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))


Welcome to PPCG! – Laikoni – 2018-03-19T09:16:45.290

2

# Python 3, 78 72 bytes

import re
lambda x:re.sub("[Aa](.*?)(a|A|$)",lambda m:m[1].swapcase(),x)  You can use m[1] in place of m.group(1) on Python 3.6+. – Bubbler – 2018-03-15T00:04:11.573 Why was this flagged as low quality…? – Nissa – 2018-03-15T00:21:33.527 I have no idea ... – pppery – 2018-03-15T00:22:21.723 1New posts are flagged automatically if they are short and contain no text. Adding a description usually prevents that. – mbomb007 – 2018-03-15T00:35:48.463 And now I wonder how many "A"s there are supposed to be in "ppperry". – Mr Lister – 2018-03-15T11:03:51.517 Um, why should there be any? – pppery – 2018-03-17T17:38:24.583 2 # ><>, 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 :)

2

# 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:
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);
}


2

# 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!

1

# 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 !

Can reduce to 96 by not assigning input() to the variable s. Try it online!

– ElPedro – 2018-03-15T13:11:30.400

Good one @ElPedro I will edit! – Rick Rongen – 2018-03-15T13:13:12.247

1

# 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.

1

# 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~'


1

# 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!

1

# 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.

1

# 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!

65 bytes – ceilingcat – 2020-03-06T02:07:23.160

1

# 05AB1E (legacy), 11 bytes

„AaS¡εNFš]J


Try it online!

0

# 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.


0

# Pyth, 19 bytes

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


Try it here.

Saved one byte thanks to mnemonic.

0

# 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).

1You could change from from re import * to import re and x=re.split(...) to save 3 bytes. – sonrad10 – 2018-03-15T11:25:24.593

0

# Charcoal, 21 bytes

ＦＳ¿⁼a↧ι≦¬κ¿κι¿№αι↧ι↥ι


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

ＦＳ


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.

0

# 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)))


0

# APL (Dyalog Classic), 4641 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.

0

# 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!

0

# 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


0

# pwsh, 109 bytes

$Input|%{$i=$_[0]-ceq'a';$r='';foreach($s in$_.split('a')){$r+=($s.ToUpper(),$s.ToLower())[$i];$i=!$i};$r}  0 ## 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


You can replace cs by a single letter variable name and define f as an infix function.

– Laikoni – 2018-03-20T11:06:32.290

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. – Laikoni – 2018-03-20T11:10:14.777

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. – Laikoni – 2018-03-20T11:14:46.887

0

(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


@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. – Pharap – 2018-03-19T23:05:31.300

0

# 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


0

# 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...

0

# 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.

0

# 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

0

# 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))])


3

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

– Jo King – 2019-08-08T04:20:06.603

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? – Jo King – 2019-08-08T04:56:26.630

Welcome! It is recommended to add an explanation for your code, because code-only answers are usually automatically flagged as low-quality. – mbomb007 – 2019-08-08T14:41:02.617

... and there are two spaces between for i,j in and enumerate( – pppery – 2019-08-08T14:42:35.177

0

# 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?")))

))


0

# 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


## 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


0

# 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).
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


1

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

– caird coinheringaahing – 2020-10-30T00:43:33.053

@cairdcoinheringaahing whitespace is mandatory around ? and :` in the conditional operator. I removed whitespace where I could. – binarycat – 2020-10-30T02:33:01.443