199
\$\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\$
  • 110
    \$\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 '18 at 18:29
  • 5
    \$\begingroup\$ suggested test case : teSTateSTateSTateST \$\endgroup\$ – Rod Mar 14 '18 at 18:44
  • 88
    \$\begingroup\$ If only the enter key also had a notch in it so this wouldn' \$\endgroup\$ – 12Me21 Mar 14 '18 at 19:33
  • 75
    \$\begingroup\$ t happen....... \$\endgroup\$ – 12Me21 Mar 14 '18 at 19:33
  • 23
    \$\begingroup\$ Literally joined this site to upvote "Without the notch, no one can hear you scream" \$\endgroup\$ – lucasvw Mar 15 '18 at 21:10

60 Answers 60

2
\$\begingroup\$

PHP 4, 77 76 75

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.

Try it out here.


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.

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

JavaScript (ES6), 62 60 bytes

Solution

s=>s.split(/a|A/).map((x,i)=>(i%2?x.toUpperCase():x)).join``

Explanation

s.split(/a|A/) split string into array removing a's at the same time

.map((x,i)=>(i%2?x.toUpperCase():x)) make every other string in the array upper case

.join`` convert the array to a string. without any joining character

Example

f= 
s=>s.split(/a|A/).map((x,i)=>(i%2?x.toUpperCase():x)).join``

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Golf! You can save a couple bytes by replacing .join('') with .join`` \$\endgroup\$ – Oliver Aug 8 at 19:50
  • \$\begingroup\$ Thanks! I will make the edit. \$\endgroup\$ – Joel Aug 8 at 20:26
  • 1
    \$\begingroup\$ Not correct (although pretty nicely golfed), when you enter Capslock mode you need to flip the capitalisation, not just make it uppercase. \$\endgroup\$ – IQuick 143 Aug 9 at 12:32
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\$

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();
    std::io::stdin().read_line(&mut input);
    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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Giuseppe Mar 15 '18 at 12:09
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\$
  • \$\begingroup\$ Can reduce to 96 by not assigning input() to the variable s. Try it online! \$\endgroup\$ – ElPedro Mar 15 '18 at 13:11
  • \$\begingroup\$ Good one @ElPedro I will edit! \$\endgroup\$ – Rick Rongen Mar 15 '18 at 13:13
1
\$\begingroup\$

Chip, 64 bytes

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

Try it online!

How it works

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

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

 A-a

     Bb
     Cc
     Dd
     Ee
G
g
f--F

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

This is determined by:

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

The program assumes it will receive no characters above 127.

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

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

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

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

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

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

Javascript (ES6), 64 bytes

s=>s.split(/a|A/g).reduce((s,p,i)=>s+(i%2?p.toUpperCase():p),'')

Let me know if you think this is broken :)

(edit: simplified ternary)

\$\endgroup\$
  • 1
    \$\begingroup\$ This doesn't seem to work with letters that are already uppercase. \$\endgroup\$ – Yair Rand Mar 25 '18 at 19:59
1
\$\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\$
1
\$\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\$
  • 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 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 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 at 14:41
  • \$\begingroup\$ ... and there are two spaces between for i,j in and enumerate( \$\endgroup\$ – pppery Aug 8 at 14:42
1
\$\begingroup\$

Julia 1.0, 82 bytes

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

Explanation

De-golfed:

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

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

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

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

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

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

Try it online!

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

Pyth, 21 bytes

ssm+Pdr2edcscR\AcQ\a2

Try it here

Explanation

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

Pyth, 19 bytes

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

Try it here.

Saved one byte thanks to mnemonic.

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

Charcoal, 21 bytes

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

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

FS

Loop through each character in the line of input.

¿⁼a↧ι

Test whether it equals a in lower case.

≦¬κ

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

¿κ

Otherwise check whether k is currently truthy.

ι

If so then just print the character.

¿№αι

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

↧ι

If it is then print it in lower case.

↥ι

Otherwise print it in upper case.

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

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

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

APL (Dyalog Classic), 46 41 40 bytes

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

Try it online!

How??

  • 'aA'~⍨ - Remove all a's from ...
  • ⊢819⌶⍨¨2|(⊢≠819⌶¨) - ... the alternating upper-and-lower-case of the argument ...
  • +≠\∘ ... based upon ...
  • (∨⌿'aA'∘.=⊢) ... the position of a and/or A.
\$\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\$

PHP, 129 BYTES

$f=false;
foreach(str_split($str)as$l){if(strtolower($l)!='a')
{echo$v=($f)?mb_strtoupper($l):mb_strtolower($l);}else{$f=!$f;}}

Test it here

Basically it decides to write in uppercase depending on a flag everytime it encounters an 'a'

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! It seems that your code assumes that the input is given in a hardcoded variable. However, all answers need to be either full programs or callable functions. Wrapping your code in a function which takes $str as a parameter would be the simplest fix, but I don't know if PHP has shorter ways to read the input from STDIN or a command-line argument instead. \$\endgroup\$ – Martin Ender Mar 16 '18 at 17:11
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\$

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\$
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\$
  • \$\begingroup\$ @Laikoni Unfortunate. I've fixed that now at the cost of 16 more bytes, but realised I was counting Windows line endings as 2 bytes, so I've clawed back 3 bytes by switching to Unix line endings. \$\endgroup\$ – Pharap Mar 19 '18 at 23:05
0
\$\begingroup\$

Haskell, ~~199~~ 133 bytes

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

Run using f False "<string>"

Ungolfed version:

import Data.Char

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

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

Pip, 22 bytes

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

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

Try it online!

Explanation

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

Java (OpenJDK 9), 90 bytes

int j=0;for(char t:c){if(t==65||t==97)j^=1;else System.out.printf("%c",j>0&&t>65?t^32:t);}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! Submissions should be a program or function, and yours is currently a snippet. Adding c->{...} around your code mades it a valid lambda function. You can also golf || and && to | and &, and remove the {} around the for-loop. In addition, char can be int in this case. Try it online 90 bytes. Nice first answer, and enjoy your stay! Oh, and you might find Tips for golfing in Java interesting to read through. \$\endgroup\$ – Kevin Cruijssen Apr 9 '18 at 8:07
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\$

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

Your Answer

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

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