text:
(A[l(t[e(r)n]e)s]t) a string!
Alternesting, is the act of taking a string and nesting it in alternating brackets. Here is how you alternest a string.

For a string of length N, take the center N characters, and surround them in parenthesis. So if our string was Hello world! (12 characters), we'll end up with
(Hello world!)

Then, take the remaining center n-2 characters, and surround them in square brackets. In this case, the center 10 characters are ello world, so the next iteration is:
(H[ello world]!)

As long as there are more than two characters left in the middle of the string, repeat the last two steps, alternating between () and []. Here are the last steps:
(Hello world!)
(H[ello world]!)
(H[e(llo worl)d]!)
(H[e(l[l(o[ w]o)r]l)d]!)

Since there are only two characters left in the middle on the last iteration, we stop. Our final string is
(H[e(l[l(o[ w]o)r]l)d]!)

Note how there are two characters in the middle brackets. This happens when the input is an even length. If the input was an odd length (for example, Hello, world! with a comma added), we would have only one character in the middle:
(H[e(l[l(o[,( )w]o)r]l)d]!)

For today's challenge, you must write a program or function that takes a string as input, and alternests it, outputting the new string. You can take input and output in any reasonable format you like. The input will always be at least one character long, and will only contain printable ASCII. You can also assume that the input will not contain any parenthesis or square brackets. For traditional languages, this shouldn't matter too much, but it might make it easier for some esoteric languages.
As usual, this is a code-golf competition, so try to make the shortest possible answer in the language of your choice. Have fun!
Test IO
#Input                      #Output

"Alternesting is fun!"  --> (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!)
"PPCG"                  --> (P[PC]G)
"Code-golf"             --> (C[o(d[e(-)g]o)l]f)
"4 8 15 16 23 42"       --> (4[ (8[ (1[5( [1]6) ]2)3] )4]2)
"a"                     --> (a)
"ab"                    --> (ab)
"abc"                   --> (a[b]c)

Related

Must we always start with parentheses (()) or can we start with brackets ([])?

@totallyhuman It should always start with parentheses ()

Proposed testcase: HelloWorld.

Also, are trailing spaces allowed?

Python 3, 70 69 65 bytes
-1 byte thanks to @Uriel
-4 bytes thanks to @xnor
f=lambda s,b=0:s and'(['[b]+s[0]+f(s[1:-1],~b)+s[1:][-1:]+')]'[b]

Try it online!

C, 143 137 135 bytes
i,l,k;f(char*s){for(k=i=0,l=strlen(s);*s;printf("%c%c","([])"[i++%2+2*(i>l/2+!k)],*s++))i>l/2-1&&l&1^1&&putchar(*s++,k=++l);puts(")");}

Try it online!
Explanation:
// Function (and variable) declaration.
i,l,k;f(char*s){

// Start the loop and initialize the variables. The loop terminates
// when the NUL-terminator of the string is reached.
for(k=i=0,l=strlen(s);*s;<this part saved for later>)

// Check if we have reached the middle of the string. Because of the
// short-circuiting of the conditions, we don't need to use an 'if'
// statement here; if a condition is false, no further conditions
// are evaluated.
i>l/2-1&&

// Equivalent to '!(l%2)', but one byte shorter. Checks if the length
// of the string is even.
l&1^1

// If we have reached the middle and the length of the string is even,
// we'll need to skip one bracket, so we'll print the current character
// of the string and increment the pointer. Also we increment 'l' to
// avoid this getting done more than once, and give 'k' a non-zero
// value.
&&putchar(*s++,k=++l);

// The following is inside the 'increment' part of the 'for' loop.
// We print two characters. The first one is a bracket and the second
// one is the current character in the string.
printf("%c%c","([])"[i++%2+2*(i>l/2+!k)],*s++)

// The type of bracket is  chosen depending on the value of 'i'. A
// character from the string "([])" is selected with the index 'i%2 + 2',
// if we have reached the  middle of the string, and with index 'i%2', if
// we haven't.

// The exact part where this change happens depends on the parity of
// the string length, so we use 'k' to signal if the length is even or
// odd. If the length is odd, 'k==0', so '+!k' is the same as '+1'.
// Otherwise 'k' is non-zero, so '+!k' is the same as '+0'.

// Output the final ')'.
puts(")");}

If I remember C correctly, variables declared globally are initialised to 0. Thus, you shouldn't need the k=i=0,. I might be wrong. See this SO answer

@Tas You are indeed correct, but functions have to be reusable to be valid submissions, so the variables need to be initialized inside the function.

Retina, 52 bytes
+`(?<!\()[^()]+(?!\))
($&)
(\(.)\(
$1[
r`\)(.\))
]$1

Try it online! The first stage inserts pairs of parentheses between each pair of input characters, while the second and third stages correct alternate parentheses to brackets.

JavaScript (ES6), 69 68 62 bytes
-6 thanks to @Shaggy
f=([c,...s],i,l=s.pop()||s)=>c?'[('[i^=1]+c+f(s,i)+l+'])'[i]:s

Try it online!

62 bytes

@Shaggy Wow! This answer is quite old ... Thanks :)

Sed, 78
Score includes +1 for -r option passed to sed.
s/.*/(&)/
:
s/(\(.)([^][]+)(.\))/\1[\2]\3/
t
s/(\[.)([^)(]+)(.\])/\1(\2)\3/
t

Try it online.

V, 25 26 25 bytes
1 2 bytes off thanks to @DJMcMayhem
òC()Pé
%llòÍî
òF)%r[r];

Try it online!
Borrowed some of @udioca's ideas. Also finally used the surround plugin included in V for an answer, although it may not have been the best way, who knows. The plugin does NOT want to be used.
Hexdump:
00000000: e3e1 0a6b f2e9 286c 6ce9 5b6c 6cf2 6af2  ...k..(ll.[ll.j.
00000010: e129 6868 e15d 6868 f2cd ce              .)hh.]hh...

Explanation:
-> |abcdefg      (the input, where | is the cursor)
ò              ' recursively
 C()           ' (C)hange from the cursor to the end of the line to '()'
-> (|)    (where | is the cursor)
     P         ' (P)aste the changed bit (what was there) left of the cursor
-> (abcdef|g)
      é        ' nsert a newline
-> (abcdef
   |g)
%              ' Goto the previous matching parenthese
-> |(abcdef
   g)
 ll            ' Move two characters right
-> (a|bcdef
   g)
   ò           ' End recursive loop (it will break on ll when there are no characters left
-> (a(b(c
   d)
   e)
   f)
    Íî         ' Remove all newlines
-> (a(b(cd)e)f|)
ò              ' Recursively
 F)            ' Go backwards to the next )
-> (a(b(cd)e|)f)
   %r[         ' Go to the matching paren and (r)eplace it with [
-> (a|[b(cd)e)f)
               ' Go back to the previous cursor location
-> (a[b(cd)e|)f)
       r]      ' (r)eplace this paren with ]
-> (a[b(cd)e|]f)
         ;     ' repeat F)
-> (a[b(cd|)e]f)
               ' implicitly end recursion

Wow, nice job! I was stuck at 29 bytes but missing a bunch of edge cases. This is a pretty sweet answer. You can save one byte by using ; instead of the last f) Try it online!

It's actually broken right now because of spaces, I'm going to delete and fix

@DJMcMayhem Can I see your 29 byte one?  Unless you plan to golf it under me and compete, which I wouldn't be surprised about :)

It doesn't work, so I don't mind showing you it: https://tio.run/##K/v///Diwwu5sg9vOrxSIyfn8MpoILEpC8hdqJmRcXhhLJDYdLj3cN///x6pOTn5Ogrl@UU5KYoA Oh, and BTW: https://chat.stackexchange.com/transcript/message/38434285#38434285 :)

:( doing alternating () and [] is a byte shorter but way less cool

Haskell, 96 91 81 79 77 bytes
(cycle"()[]"!)
(l:r:a)!k|[x]<-k=[l,x,r]|x:y<-k=l:x:a!init y++[last y,r]|2>1=k

Try it online!

You can drop the parents around (x:y) and (init y). k==""="" is shorter as k==""=k.

Save some more bytes by changing cycle["()","[]"] to just "()[]": Try it online!

@Laikoni great suggestions,thanks

Good catch that keeping cycle is even shorter. You can still remove the parenthesis around (init y).

How would you have done it without cycle? With somethink like x="()[]"; ""!k=x!k ?

By doing the recursion with (p++[l,r])!init y, see the TIO link in my second comment.

Ah I didn't spot that link! That was clever!

You can move the case k==""=k to the end and change it to 0<1=k.

Javascript(ES6) 110 105 bytes
Thanks to @powelles for reminding me about x%y<1.
Thanks @Luke for a-b?y:x
i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d-b?(d%1==0?!e:e)?')':']'):'').join``

let f=i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d==b?'':(d%1==0?!e:e)?')':']')).join``
<input onkeyup="result.textContent = f(this.value)"/>

The first thing in understanding this beast is ungolfing it:
function alternest(input) { //input is i in the original
  let inputArray = Array.from(input); //the [...i] section
  let result = inputArray.map((item, index, baseArray) => { //result is an added helper variable
    let middle = input.length / 2 - 1, //the middle of the string
        alternate = index % 2 == 0; //should you alternate from '(' and '[' or ')' and ']'

    let symbol; //the alternating symbol

    if(middle > index) { //if its opening braces
      symbol = alternate ? '[' : '(';
    } else if(middle < index) {
      if(middle % 1 === 0) //if middle is a whole number
        alternate = !alternate; //reverse alternate
      symbol = alternate ? ')' : ']';
    } else { //if middle === index
      symbol = ''; //there's no symbol in the center for even alternests
    }
    return item + symbol; //convert the array item into the item and symbol
  }).join('');

  return '(' + result; //add the first symbol.
}

Almost every line is a part of the golfed version, so stepping through:
Line 1: The function statement becomes an arrow function, renaming input to i. Becomes i=>.
Line 2: Array.from is the new, proper way of converting a string into an array, and what we use in on this line. However along with it, the spread operator is a cheaper way than the old .split('') way, to do it, which is what is used in the golfed version. Ends up as [...i].
Line 3: .map loops through an array, giving you three arguments: item(a in the golfed), index; golfed as b, and baseArray or c. While we only care about item and index, we kept baseArray(see line 4 for why). Golfs to .map((a,b,c,...)=>....
Line 4: The variable middle, the or the argument d in the golfed version is created to save a few bytes when it is repeated. The argument c had to be kept for argument d to be created. Is converted to (...,d=i.length/2-1,...).
Line 5: The variable alternate, or argument e is used to check what character it was on "(" or "[" or if it was past the middle, ")" and "]". b%2<1 is equal to b%2==0 because it can't be anything less than 1, but 0 in this case. Equals (...,e=b%2<1).
Line 6: A helper variable to allow me to convert the ternary operators to if statements. Isn't anything in the actual codegolf.
Lines 7-8: If the index is less than the middle of the string set the symbol to an alternation of "[" and "(". Equates to d>b?e?'[':'(':....
Lines 9-12: Else (if index is greater than middle), check if middle is a whole number, if so switch the alternation. Then set the symbol to an alternation of ')' and ']'. Obfuscated to (d%1==0?!e:e)?')':']'.
Lines 13-15:If the in the middle set the symbol to an empty string. This doesn't apply to odd alternesters, because middle has a decimal. Becomes: d==b?'':....
Line 16: Joins the character array back into a string. Equates to .join``.
Line 17: Returns the starting symbol "(" and the result. Correlates to '('+....

For some simple wins you could change %2==0 to %2<1 and use [...i] instead of i.split

Thanks @powelles I've been working on an explanation more than a fully golfed answer, so that hasn't made it into an edit yet. I already had the [..i] idea, but I forgot about %2<1 thanks.

b%2<1 could be replaced by !b%2

Also, d==b?x:y could become d-b?y:x and d%1==0 could become !d%1.

Unfortunately because of order of operations !d%1 only works with parentheses: !(d%1), and it doesn't shave off any bytes. I forgot that 0 was the only falsy number, for some reason I thought -1 was the falsy one.
Correct me if I'm getting something wrong about the second one.

Ruby, 79 77 bytes
-2 bytes thanks to @Value Ink
->s{z=s.size
(z/2+z%2).times{|i|s.insert k=i*2,'(['[i%2]
s[~k]+=')]'[i%2]}
s}

Try it online!

s.insert k=i*2,'(['[i%2];s[~k]+=')]'[i%2] to save 2 bytes. Try it online!

Jelly, 23 21 bytes
LHĊRị
ç⁾)]żUFUż@ç⁾([$

Try it online!
LHĊRị           - helper function. Takes inputs of the input string and list of brace types
L                 - length of the input string
 HĊ               - number of parenthesis/brackets facing a single direction
   R              - range
    ị             - indexed into right argument: list of brace types ')]' or '(['

ç⁾)]żUFUż@ç⁾([$ - main function
ç⁾)]              - get list of left-facing parentheses/brackets
    żU            - zip to the end (U) of the input string
      FU          - move the beginning of the string back to the beginning
        ż@        - zip with (to the start of the string):
          ç⁾([$   -the list of right-facing parentheses/brackets to the beginning

-2 bytes thanks to @EricTheOutgolfer

You can remove a line, and move the ị to the helper link for -2, like this: LHĊRị¶ç⁾)]żUFUż@ç⁾([$

C++ 14, 154 145 134 bytes
(Thanks to ideas by ceilingcat for extra bytes 145->134)
[Recursive]
#include <regex>
using S=std::string;S L(S i,int b=1){int l=i.size();return"(["[b]+(l<3?i:i[0]+L(i.substr(1,l-2),!b)+i[l-1])+"])"[b];}

C++ 14, 177 bytes
[Iterative]
auto l(string s){int z=s.length();string r(z*2+z%2,'-');int i=0;for(;i<z;i+=2)r[i]=i/2%2?'[':'(',r[i+1]=s[i/2];for(i=z;i<2*z;i+=2)r[i]=s[i/2],r[i+1]=(i+1)/2%2?')':']';return r;}

Perl, 77 74 (73 + 1) bytes
Regular expressions are glorious things. Run with the -p command line flag.
$x=qr/[^]()[]/;$z=qr/(^|$x)\K($x+)($|$x)/;s/$z/[$2]$3/ while s/$z/($2)$3/

05AB1E, 31 bytes
2ä`Rð«„)]Ig©×øRJ®Èƒ¦}s„([®×søJì

Try it online!
Explanation
With examples for input: abcd / abcde
2ä`                              # split input to 2 separate parts on stack
                                 # RESULT: 'ab','cd' / 'abc', 'de'
   R                             # reverse the second part
    ð«                           # append a space
      „)]                        # push the string ")]"
         Ig©×                    # repeat it len(input) times
             ø                   # zip with the second part of the input string
              RJ                 # reverse and join to string
                                 # RESULT:  ' )c]d)' /  ' )d]e)'
                ®Èƒ¦}            # remove the first (1,2) chars for (odd,even) length input
                                 # RESULT: 'c]d)' / ')d]e)'
                     s           # swap the first part of the input string to top of stack
                      „([®×      # repeat the string "([" len(input) times
                           sø    # zip with first part of input string
                                 # RESULT: ['(a', '[b'] / ['(a', '[b', '(c']
                             Jì  # join to string and prepend to the second part

SCALA, 140 138 chars, 140 138 bytes
I'm sorry I couldn't do better ... I'm sure there are many ways to improve it.
Still:
val n=s.length-1
var l=""
var r=""
for(i<-0 to n/2){l+=(if(i%2<1)"("else"[")
if(i!=n-i)l+=""+s(i)
r=""+s(n-i)+(if(i%2<1)")"else"]")+r}
l+r

Try it online!
Thanks for this challenge, that was quite hard for me.
EDIT : -2 bytes thanks to Mar Dev.
PS : I will ask something though. I understand why THIS CODE keeps duplicating the central char of my string if I have an odd length (I just don't check and add it twice, in both l and r strings). But why do I get a pair of parenthesis when I try correcting it like THAT? I don't understand at all.

You can change the i%2==0 to i%2<1 to save two bytes.

Ruby, 57 bytes
f=->s,i=0{a,*b,c=s;a ?["(["[i],a,*f[b,~i],*c,")]"[i]]:''}

Try it online!
Recursive function similar in spirit to ovs's Python answer. Inputs and outputs arrays of characters.
Note that we could shave off 3 more bytes, and in the test suite on TIO, where we join the arrays back to strings, the visible result would look unchanged:
f=->s,i=0{a,*b,c=s;a ?["(["[i],a,f[b,~i],c,")]"[i]]:p}

However, this would produce nested arrays and nils in the raw output, which is probably too weird for a "reasonable" output format.

05AB1E, 49 42 bytes
g;îD„([×s£©"s‚.Bøvy¬ðQi¦}}JR"DU.V®D∞sKRX.V

Try it online!

QuadR, 82 bytes
(81 bytes +1 for ≡ flag)
(\(.)([^[])(.+?)([^\]])(.\))
(\(.)(..?)(.\))
^[^\(].*
\1[\2(\3)\4]\5
\1[\2]\3
(&)

Try it online!

AWK, 118 bytes
{b=")";for(j=l=length(c=$0);j>0;){x=substr(c,j--,1);b=(j>l/2?(((d=!d)?"]":")")x):j==l/2?x:((d=!d)?"(":"[")x)b}print b}

Tested with gawk, but it should work with any compliant awk interpreters
$ awk -f alternesting.awk <<< 'abc'
(a[b]c)

Java (OpenJDK 8), 124 bytes
c->{String s="";for(int l=c.length-1,a=l/2;a>=0;)s=(a%2<1?"(":"[")+(a<-~l/2?c[a]+s+c[l-a]:c[a])+(a--%2<1?")":"]");return s;}

Try it online!
Credits

-2 bytes thanks to ceilingcat.

JavaScript, 101 bytes
Not a winner, but it was interesting to try the replace approach. This could definitely be improved, but it got out of hand quick...
s=>"("+s.replace(/./g,(a,b)=>a+(l%2|b*2+2!=l?")][("[3*(c=l>(b+=l%2-1)*2+2)+(b-c*l)%2]:""),l=s.length)

PowerShell, 125 119 111 bytes
{param($s)for($p='()[]';($f,$s,$g=$s-split'(?<=.)(.+)(?=.)')[0]){$l+=$p[$i++]+$f;$r=$g+$p[$i++]+$r;$i%=4}$l+$r}

Try it online!
Previous version*
{for($s="($args)";$s-ne($t=$s-replace'(\(.)([^][]+)(.\))','$1[$2]$3'-replace'(\[.)([^)(]+)(.\])','$1($2)$3')){$s=$t}$s}

*Thanks @Digital Trauma.

Pyth, 42 (!) bytes
M?!lHH+@,\[\(G++hHg!GPtH+?qlH1keH@,\]\)Gg1

Test it online! The input must be quoted.
Explanations
M                                             # Define a function g with arguments G and H
 ?!lHH                                        # If len(H) == 0, return H. Otherwise...
      +@,\[\(G                                # Concatenate [ or ( to...
               +hHg!GPtH                      # ...to H[0] concatenated to g(not(G), H[1:-1]), itself concatenated...
              +          ?qlH1keH             # ...to H[-1] if len(H) != 1, otherwise to "" (that's for odd length input strings)...
                        +        @,\]\)G      # ...and to that concatenate ] or ).
                                        g1    # Call g(True, Q). Q is implicit input

So basically I progressively remove the head and end of H (being the input string in the beginning) while concatenating the parentheses/brackets. G is just a boolean which remembers if I must use brackets or parentheses.

Stax, 25 bytes
ò≥◘■O║£/öτt≈K↔ì♂≈-⌂6=═°!b

Run and debug it

JavaScript (Node.js), 77 bytes
Not the best JS solution, but it could interest some people : this solution uses recursive calls with inversion of the 2 optional parameters at each step to alternate between () and []
f=(s,a="()",b="[]")=>a[0]+(s[2]?s[0]+f(s.slice(1,-1),b,a)+s.slice(-1):s)+a[1]

Try it online!

Japt, 28 bytes
Initially inspired by Arnauld's solution.
V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U

Try it
V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U     :Implicit input of string U
V                                :Second input variable, defaulting to 0
 °                               :Postfix increment
  g                              :Index, 0-based & modular, into
   "()[]"ò                       :  Length 2 partitions of string "()[]"
          )                      :End indexing
           i1                    :Insert at 0-based index 1
             ¢                   :  Slice first 2 characters off U
              ?                  :  If truthy (non-empty string) return
               UÌ                :    Last character of U
                 i               :    Prepend
                  UÎ             :      First character of U
                    +            :      Append
                     ß           :        Recursive call with argument (V is passed automatically)
                      Us1        :          U sliced from index 1 to index
                         J       :          -1
                          :U     :  Else return U


text:
Kolakoski Reduction
Overview
Some of you might be aware of the Kolakoski Sequence (A000002), a well know self-referential sequence that has the following property:

It is a sequence containing only 1's and 2's, and for each group of 1's and twos, if you add up the length of runs, it equals itself, only half the length. In other words, the Kolakoski sequence describes the length of runs in the sequence itself. It is the only sequence that does this except for the same sequence with the initial 1 deleted. (This is only true if you limit yourself to sequences made up of 1s and 2s - Martin Ender)

The Challenge
The challenge is, given a list of integers:

Output -1 if the list is NOT a working prefix of the Kolakoski sequence.
Output the number of iterations before the sequence becomes [2].

The Worked Out Example
Using the provided image as an example:
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1] # Iteration 0 (the input).
[1,2,2,1,1,2,1,2,2,1,2]             # Iteration 1.
[1,2,2,1,1,2,1,1]                   # Iteration 2.
[1,2,2,1,2]                         # Iteration 3.
[1,2,1,1]                           # Iteration 4.
[1,1,2]                             # Iteration 5.
[2,1]                               # Iteration 6.
[1,1]                               # Iteration 7.
[2]                                 # Iteration 8.

Therefore, the resultant number is 8 for an input of [1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1].
9 is also fine if you are 1-indexing.

The Test Suite (You can test with sub-iterations too)
------------------------------------------+---------
Truthy Scenarios                          | Output
------------------------------------------+---------
[1,1]                                     | 1 or 2
[1,2,2,1,1,2,1,2,2,1]                     | 6 or 7
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1]       | 8 or 9
[1,2]                                     | 2 or 3
------------------------------------------+---------
Falsy Scenarios                           | Output
------------------------------------------+---------
[4,2,-2,1,0,3928,102904]                  | -1 or a unique falsy output.
[1,1,1]                                   | -1
[2,2,1,1,2,1,2] (Results in [2,3] @ i3)   | -1 (Trickiest example)
[]                                        | -1
[1]                                       | -1

If you're confused:
Truthy: It will eventually reach two without any intermediate step having any elements other than 1 and 2. – Einkorn Enchanter 20 hours ago
Falsy: Ending value is not [2]. Intermediate terms contain something other than something of the set [1,2]. A couple other things, see examples.

This is code-golf, lowest byte-count will be the victor.

Can we use any falsey value instead of just -1?

Can we know for certain that all of the list entries in the input will be positive?

@WheatWizard Did you read all the test cases?

@Okx Ah I missed the -2 there.  Rather unfortunate costs me a ton of bytes.

@Okx Haskell, my answer is below.

What do you mean by "NOT a working prefix of the Kolakoski sequence"? I had assumed you meant the list does not eventually reach [2] until I saw the [2,2,1,1,2,1,2] test case.

@ngenisis It  will eventually reach two without any intermediate step having any elements other than 1 and 2.

Might be a good idea to add [1] as a test case.

Will truthy test cases always start with a 1?

@Christian: No. For example [2], [2,2] and [2,2,1] are all truthy.

@mbomb007 any distinct value is fine. A positive integer is not fine. If you're 1-indexing 0 is fine. "False" is fine. Erroring is fine. Any non-positive return value is fine, even -129.42910.

@MagicOctopusUrn If the falsy value isn't specific but can vary (except from being a positive integer, e.g. be a list), would it be valid?

@EriktheOutgolfer I'd need an example

@MagicOctopusUrn For example, being able to return any inconsistent list for falsy (e.g. [3, 4], [7, -100, 8.5], [1, 2, 2, 1] etc.) and a positive number for truthy.

@EriktheOutgolfer yeah, that should be fine, as long as the truthy value is consistent and you define all other outputs as falsy.

@MagicOctopusUrn Alright, now my answer returns a list for falsy inputs and a positive integer for truthy ones.

I think that the empty list is an unnecessary complication. You state: given a list of integers. Nothing is not an integer. Please consider removing the fourth falsy scenario.

Haskell, 126 87 79 76 75 bytes
39 bytes saved thanks to Ørjan Johansen
import Data.List
f[2]=0
f y@(_:_:_)|all(`elem`[1,2])y=1+f(length<$>group y)

Try it online!
This errors on bad input.

f (and consequently !) can be shortened a lot by using lazy production + span/length instead of accumulators. Try it online!

Seem to enter an infinite loop for [1]

@Emigna Darn.  It costs me 6 bytes to fix it, but I've fixed it.

@ØrjanJohansen That seems like a good tip, but I'm not proficient enough in Haskell to understand whats going on there.  If you want you can post it as your own answer but at least as long as I don't know how your solution works, I'm not going to add it to my answer. :)

I then realized this is a case where an import is actually shorter (and also simpler to understand): import Data.List;f l=length<$>group l. (<$> is a synonym for map here.) Also, instead of having two different -1 cases it is shorter to use a @(_:_:_) pattern to force the main case to only match length >=2 lists. Try it online!

Sorry if my comment edits were confusing, somehow my TIO and my comment got unsynchronized.

05AB1E, 22 bytes
[Dg2‹#γ€gM2›iX]2QJiNë®

Try it online!
Explanation
[                        # start a loop
 D                       # duplicate current list
  g2‹#                   # break if the length is less than 2
      γ                  # group into runs of consecutive equal elements
       €g                # get length of each run
         M2›iX           # if the maximum run-length is greater than 2, push 1
              ]          # end loop
               2QJi      # if the result is a list containing only 2
                   N     # push the iteration counter from the loop
                    ë®   # else, push -1
                         # implicitly output top of stack

Fails for [1,1,2,2,1,2,1,1,2,2,1,2,2,1,1,2,1,1]

@WeijunZhou: Thanks, fixed!

You may have forgotten to update the link ...

@WeijunZhou: Indeed I had. Thanks again :)

Jelly, 17 bytes
ŒgL€$ÐĿµẎḟ1,2ȯL_2

Try it online!

SCALA, 290(282?) chars, 290(282?) bytes
It took me sooo loong ... But I'm finally done!
with this code :
var u=t
var v=Array[Int]()
var c= -1
var b=1
if(!u.isEmpty){while(u.forall(x=>x==1|x==2)){c+=1
if(u.size>1){var p=u.size-1
for(i<-0 to p){if(b==1){var k=u(i)
v:+=(if(i==p)1 else if(u(i+1)==k){b=0
if(p-i>1&&u(i+2)==k)return-1
2}else 1)} else b=1}
u=v
v=v.take(0)}else if(u(0)==2)return c}}
c

I don't know if I should count the var u=t into the bytes, considering I do not use t during the algorithm (the copy is just to get a modifyable var instead of the parameter t considered as val - thanks ScaLa).
Please tell me if I should count it.
Hard enough. Try it online!
PS : I was thinking of doing it recursively, but I'll have to pass a counter as a parameter of the true recursive "subfunction" ; this fact makes me declare two functions, and these chars/bytes are nothing but lost.
EDIT : I had to change (?) because we're not sure we should take in count [1] case. So here is the modified code :
var u=t
var v=Array[Int]()
var c= -1
var b=1
if(!u.isEmpty){try{t(1)}catch{case _=>return if(t(0)==2)0 else -1}
while(u.forall(x=>x==1|x==2)){c+=1
if(u.size>1){var p=u.size-1
for(i<-0 to p){if(b==1){var k=u(i)
v:+=(if(i==p)1 else if(u(i+1)==k){b=0
if(p-i>1&&u(i+2)==k)return-1
2}else 1)} else b=1}
u=v
v=v.take(0)}else if(u(0)==2)return c}}
c

It's not optimized (I have a duplicate "out" for the same conditions : when I get to [2] and when param is [2] is treated separatedly).
NEW COST = 342 (I didn't modify the title on purpose)

Seem to enter an infinite loop for [1]

Yep, but as said by the OP (as I understood at least) : "with the initial 1 deleted" and "Output the number of iterations before the sequence becomes [2]"

To my understanding, [1] never reaches [2] and should thus return -1.

I see. So do you think I should put a litte condition at start? Thanks for your advice.

I don't know scala but I assume you can just modify the loop to stop when the length of the list is smaller than 2. You already seem to have the check that the element is 2 at the end.

I'm editing, but it costs high price. I won't modify the byte cost for now on, let's see what happens. But thank you for pointing it out. Still, I could work on what I just did, I have a duplicate "out" for the same conditions : when I get to [2] and when param is [2] is treated separatedly. WIP

Could you perhaps do something like this to save some bytes?

Sadly, ScaLa's break syntax is expensive. Looks like this if you don't count the import scala.util.control.Breaks._

You could do return-1 instead of the break then.

True @Emigna I'll work on it

Jelly, 26 25 22 21 20 bytes
FQœ-2R¤
ŒgL€µÐĿṖ-LÇ?

Try it online!
This code actually wasn't working correctly until 20 bytes and I didn't even notice; it was failing on the [2,2] test case. Should work perfectly now.

Jelly, 12 bytes
ŒɠƬµ2Wea’ỊȦƊ

Try it online!
How it works
ŒɠƬµ2Wea’ỊȦƊ - Main link. Takes a list L on the left
  Ƭ          - Until reaching a fixed point, keeping each step:
Œɠ           -   Get the lengths of consectuively equal groups of elements
   µ         - Call this list S and use it as the argument
    2W       - Yield [2]
      e      - Is [2] in S?
           Ɗ - Last 3 links as a monad f(S):
        ’    -   Decrement every integer in S
         Ị   -   Insignificant? Replace 0 and 1 with 1, everything else 0
          Ȧ  -   Any and all? S is non-empty and has no zeros
       a     - Both are true?

JavaScript, 146 142 bytes
First try in code golfing, it seems that the "return" in the larger function is quite tedious...
Also, the checking of b=1 and b=2 takes up some bytes...
Here's the code:
f=y=>{i=t=!y[0];while(y[1]){r=[];c=j=0;y.map(b=>{t|=b-1&&b-2;if(b-c){if(j>0)r.push(j);c=b;j=0}j++});(y=r).push(j);i++}return t||y[0]-2?-1:0^i}

Explanation
f=y=>{/*1*/}                                        //function definition

//Inside /*1*/:
  i=t=!y[0];                                        //initialization
                                                    //if the first one is 0 or undefined,
                                                    //set t=1 so that it will return -1
                                                    //eventually, otherwise i=0
  while(y[1]){/*2*/}                                //if there are 2+ items, start the loop

  //Inside /*2*/:
    r=[];c=j=0;                                     //initialization
    y.map(b=>{/*3*/});                              //another function definition

    //Inside /*3*/:
      t|=b-1&&b-2;                                  //if b==1 or b==2, set t=1 so that the
                                                    //entire function returns -1
      if(b-c){if(j>0)r.push(j);c=b;j=0}             //if b!=c, and j!=0, then push the
                                                    //count to the array and reset counter
      j++                                           //counting duplicate numbers

    (y=r).push(j);i++                               //push the remaining count to the array
                                                    //and proceed to another stage

  return t||y[0]-2?-1:0^i                           //if the remaining element is not 2, or
                                                    //t==1 (means falsy), return -1,
                                                    //otherwise return the counter i

Test data (using the given test data)
l=[[1,1],[1,2,2,1,1,2,1,2,2,1],[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1],[1,2],[4,2,-2,1,0,3928,102904],[1,1,1],[2,2,1,1,2,1,2],[]];
console.log(l.map(f));
//Output: (8) [1, 6, 8, 2, -1, -1, -1, -1]

Edit 1: 146 -> 142: Revoking my edit on reducing bytes, because this affects the output; and some edit on the last statement

f=a=>{for(i=t=!a[0];a[1];)r=[],c=j=0,a.map(a=>{t|=a-1&&a-2;a-c&&(0<j&&r.push(j),c=a,j=0);j++}),(a=r).push(j),i++;return t||a[0]-2?-1:0^i} saves 5 bytes (for loop instead of while; commas vs braces; && vs if). You can use google's closure compiler (https://closure-compiler.appspot.com) to get these optimisations done for you

JavaScript (ES6), 127 126 95 80 bytes
g=(a,i,p,b=[])=>a.map(x=>3>x&0<x?(x==p?b[0]++:b=[1,...b],p=x):H)==2?i:g(b,~~i+1)

0-indexed. Throws "ReferenceError: X is not defined" and "InternalError: too much recursion" on bad input.
Test cases

g=(a,i,p,b=[])=>a.map(x=>3>x&0<x?(x==p?b[0]++:b=[1,...b],p=x):H)==2?i:g(b,~~i+1)

function wrapper(testcase) {
  try {console.log(g(testcase))} catch(e) {
    console.log("Error")
  }
}

wrapper([1,1])
wrapper([1,2,2,1,1,2,1,2,2,1])
wrapper([1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1])
wrapper([1,2])
wrapper([4,2,-2,1,0,3928,102904])
wrapper([1,1,1])
wrapper([2,2,1,1,2,1,2])
wrapper([])
wrapper([1])

Scala 3 (compile-time), 460 bytes
This may be the longest answer here, but it's also the fastest one here...because it works at compile time.
import compiletime.ops.int._
type r[T,P]=T match{case h*:t=>r[t,h*:P]case E=>P}
type E=EmptyTuple
type F[K,R,L,S,P,I]=K match{case E=>L-S match{case 0=>R match{case E=>0 case _=>F[r[R,E],E,0,0,0,I+1]}case _=>0}case P*:_=>0
case 1*:1*:t=>F[t,2*:R,L+2,S+2,1,I]case 1*:t=>(t,R)match{case(E,E)=>0 case _=>F[t,1*:R,L+1,S+1,1,I]}case 2*:2*:t=>F[t,2*:R,L+2,S+2,2,I]case 2*:t=>(t,R)match{case(E,E)=>I+1 case _=>F[t,1*:R,L+1,S+1,2,I]}case _=>0}
type G[K]=F[K,E,0,0,0,0]

Try it in online!
You can invoke it as G[1 *: 2 *: EmptyTuple] (actually, just G[(1, 2)] should also work, but for whatever reason, it's not working right now. I'll fix it later, though). It's 1-indexed, and it returns 0 for falsy inputs.

Python 2, 184 163 156 bytes

@Felipe Nardi Batista saved 21 bytes!!!! thanks a lot!!!!
Halvard Hummel saved 7 bytes!! thanks

Python 2, 156 bytes
a,c=input(),0
t=a==[]
while 1<len(a)and~-t:
 r,i=[],0
 while i<len(a):
	j=i
	while[a[j]]==a[i:i+1]:i+=1
	r+=[i-j]
 a=r;c+=1;t=any(x>2for x in a)
print~c*t+c

Try it online!
Explanation:
a,c=input(),0                             #input and initialize main-counter

t=a==[]                                   #set t to 1 if list's empty.

while len(a)>1:                           #loop until list's length is 1.

 r,i=[],0                                 #Initialize temp. list and
                                          #list-element-pointer

 while i<len(a):                          #loop for the element in list

  j=0                                     #set consecutive-item-counter to 0

  while(i+j)<len(a)and a[i]==a[i+j]:j+=1  #increase the consec.-counter

  r+=[j];i+=j                             #add the value to a list, move the
                                          #list-element-pointer

 a=r;c+=1;t=any(x>2for x in a)            #update the main list, increase t
                                          #the counter, check if any number
 if t:break;                              #exceeds 2 (if yes, exit the loop)

print[c,-1][t]                            #print -1 if t or else the
                                          #counter's
                                          #value

156 bytes

Clojure, 110 bytes
#(if-not(#{[][1]}%)(loop[c % i 0](if(every? #{1 2}c)(if(=[2]c)i(recur(map count(partition-by + c))(inc i))))))

A basic loop with a pre-check on edge cases. Returns nil for invalid inputs. I did not know (= [2] '(2)) is true :o

Python 2, 146 bytes (function only)
f=lambda l,i=0:i if l==[1]else 0if max(l)>2or min(l)<1else f([len(x)+1for x in"".join(`v!=l[i+1]`[0]for i,v in enumerate(l[:-1])).split("T")],i+1)

Returns 0 on falsy input (ok since it's 1-indexed). Simply use it like this:
print(f([1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1]))

Mathematica, 82 bytes
FixedPointList[#/.{{2}->T,{(1|2)..}:>Length/@Split@#,_->0}&,#]~FirstPosition~T-1&

Function which repeatedly replaces {2} with the undefined symbol T, a list of (one or more) 1s and 2s with the next iteration, and anything else with 0 until a fixed point is reached, then returns the FirstPosition of the symbol T in the resulting FixedPointList minus 1. Output is {n} where n is the (1-indexed) number of iterations needed to reach {2} for the truthy case and -1+Missing["NotFound"] for the falsy case.
If the output must be n rather than {n}, it costs three more bytes:
Position[FixedPointList[#/.{{2}->T,{(1|2)..}:>Length/@Split@#,_->0}&,#],T][[1,1]]-1&

R, 122 bytes
a=scan()
i=0
f=function(x)if(!all(x%in%c(1,2)))stop()
while(length(a)>1){f(a)
a=rle(a)$l
f(a)
i=i+1}
if(a==2)i else stop()

Passes all test cases. Throws one or more errors otherwise. I hate validity checks; this code could have been so golfed if the inputs were nice; it would be shorter even in case the input were a sequence of 1’s and 2’s, not necessarily a prefix of the Kolakoski sequence. Here, we have to check both the initial vector (otherwise the test case [-2,1]) would have passed) and the resulting vector (otherwise [1,1,1] would have passed).

Python 2, 122 bytes
def f(s,c=2,j=0):
 w=[1]
 for i in s[1:]:w+=[1]*(i!=s[j]);w[-1]+=i==s[j];j+=1
 return(w==[2])*c-({1,2}!=set(s))or f(w,c+1)

Try it online!
Python 3, 120 bytes
def f(s,c=2,j=0):
 w=[1]
 for i in s[1:]:w+=[1]*(i!=s[j]);w[-1]+=i==s[j];j+=1
 return(w==[2])*c-({1,2}!={*s})or f(w,c+1)

Try it online!
Explanation
A new sequence (w) is initialized to store the next iteration of the reduction. A counter (c) is initalized to keep track of the number of iterations.
Every item in the original sequence (s) is compared to the previous value. If they are the same, the value of the last item of (w) is increased with 1. If they are different, the sequence (w) is extended with [1].
If w==[2], the counter (c) is returned. Else, if the original sequence (s) contains other items than 1 and 2, a value -1 is returned. If neither is the case, the function is called recursively with the new sequence (w) as (s) and the counter (c) increased by 1.

To save a byte, I'm trying to combine the first two lines into def f(s,c=2,j=0,w=[1]):, but that gives a different result. Could anybody explain why that is?

Mutable default arguments will stay mutated

@JoKing That makes perfect sense, thanks!

Stax, 26 bytes
äE⌐+É7∩ΦΓyr╔ßΣ·φƒÇe►ef%I»

Run and debug it
Tried with a generator, but it seems like a while loop is shorter.

R, 93 92 bytes
Edit: -1 byte thanks to Giuseppe
f=function(x)`if`(sum(x|1)<2,(-1)^(sum(x)!=2),`if`(!all(x%in%1:2),-1,(y=f(rle(x)$l))+(y>0)))

Try it online!
Returns 1-based number of iterations for truthy input, and -1 for all falsy inputs.  This needed quite careful input testing, especially for the last two test cases...
Commented:
f=function(x)           # recursive function with argument x
`if`(sum(x|1)<2,        # if there's one (or less) element left
  (-1)^(sum(x)!=2),     # return 1 if it's equal to 2, -1 otherwise
  `if`(!all(x%in%1:2),  # if any element isn't 1 or 2
    -1,                 # return -1
    (y=f(               # otherwise recursively call self with
      rle(x)$l))        # lengths of groups of digits in x
      +(y>0)))          # if result is positive, return result +1
                        # otherwise return result (which must be -1)

R, 74 66 bytes
f=function(x)`if`(sum(x)==2&x==2,1,if(all(x%in%1:2))f(rle(x)$l)+1)

Try it online!
...but then I read the comments more carefully and realised that it's Ok to output nothing, or rubbish, or to error for falsy inputs.  That makes it much easier!

in your first answer, length(x) should be sum(x|1), and in your second, I think sum(x)==2 can be shortened to sum(x)<3.

@Giuseppe - I thought I'd tried both of those... doesn't sum(x|1) fail for zero-length vectors, and sum(x)<3 fail for vectors containing negative elements?

I think the sum(x|1) still works for 0-length vectors, but I guess I hadn't thought about negative elements.

@Giuseppe - You're right re:sum(x|1)!  Thanks!  I'd made the mistake of using c() for test case 8 (which returns NULL and fails) instead of numeric() to properly make a zero-length vector.

Vyxal, 30 bytes
λĠvL&›Dƛ2>;A$Ḣ∧[x|u£];†h2=[¥|u

Try it Online!
A big mess.

Ruby, 81 77 bytes
f=->a,i=1{a[1]&&a-[1,2]==[]?f[a.chunk{|x|x}.map{|x,y|y.size},i+1]:a==[2]?i:0}

Try it online!
Edit: Saved 4 bytes by converting to recursive lambda.
Returns 1-indexed number of iterations or 0 as falsey.
Makes use of Ruby enumerable's chunk method, which does exactly what we need - grouping together consecutive runs of identical numbers. The lengths of the runs constitute the array for the next iteration. Keeps iterating while the array is longer than 1 element and no numbers other than 1 and 2 have been encountered.

Pyth, 45 bytes
L?||qb]1!lb-{b,1 2_1?q]2b1Z.V0IKy~QhMrQ8*KhbB

Try it online!
This is probably still golfable.
It's definitely golfable if .? worked the way I hoped it would (being an else for the innermost structure instead of the outermost)
L?||qb]1!lb-{b,1 2_1?q]2b1Z # A lambda function for testing an iteration of the shortening
L                           # y=lambda b:
 ?                          # if
    qb]1                    #    b == [1]
   |    !lb                 #      or !len(b)
  |         {b              #        or b.deduplicate()
           -  ,1 2          #             .difference([1,2]):
                  _1        #               return -1
                    ?q]2b1Z # else: return 1 if [2] == b else Z (=0)

.V0                         # for b in range(0,infinity):
   IKy~Q                    # if K:=y(Q :=        (applies y to old value of Q)
        hM                  #    map(_[0],
          rQ8               #               run_length_encode(Q)):
             *Khb           #    print(K*(b+1))
                 B          #    break

Perl 5 -p, 71 bytes
$_.=$";s/(. )\1*/$&=~y|12||.$"/ge&$.++while/^([12] ){2,}$/;$_=/^2 $/*$.

Try it online!
1-indexed.  Outputs 0 for falsy.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Remove Spaces, Maintaining Capitalization
Your input will be an English sentence, phrase, or word. It will only contain a-zA-Z' -,.!?. Your task is to take the input, remove spaces, and then redistribute capitalization such that letters at indexes that were capitalized before (and only letters at indexes that were capitalized before) are capitalized.
For example, if the input is A Quick Brown Fox Jumped Over The Lazy Dog, the (0-based) indexes of the capital letters are 0, 2, 8, 14, 18, 25, 30, 34, 39. Next, remove spaces from the input: AQuickBrownFoxJumpedOverTheLazyDog. Next, lowercase all letters, but uppercase those at 0, 2, 8, 14, 18, 25, 30, 34, 39: AqUickbrOwnfoxJumpEdovertHelazYdog, which is your output.
Input
Your input will be an English sentence, phrase, or word. It can only contain lowercase letters, uppercase letters, hyphens, apostrophes, commas, periods, question marks, exclamation marks, and spaces.
Output
The input with spaces removed, lowercase-d, with letters at the index of capital letters in the input uppercase-d.
NOTE: Your program cannot crash (error such execution terminates) with an IndexOutOfRange or similar error.
Test Cases
Hi! Test!
Hi!tEst!

A Quick Brown Fox Jumped Over The Lazy Dog
AqUickbrOwnfoxJumpEdovertHelazYdog

testing TESTing TeStING testing testing TESTING
testingtESTIngteStInGTEstingtestingtestiNG

TESTING... ... ... success! EUREKA???!!! maybe, don't, NOOOOO
TESTING.........success!eureKA???!!!maybe,don't,nooooo

Enter        PASSWORD ---------
Enterpassword---------

A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Z z
AabbCcddEeffGghhIijjKkllMmnnOoppQqrrSsttUuvvWwxxZz

  TEST
teST

Sandbox

'For example, if the input is "A Quick Brown Fox Jumped Over The Lazy Dog", the (0-based) indexes of the capital letters are 0, 2, 8, 14, 18, 23, 27, 32' They are 0, 2, 8, 14, 18, 25, 30, 34, 39

@LukeSawczak thank you, my bad

Traling spaces not allowed, I assume?

@LuisMendo your assumption is correct. This is code-golf, right? :P

Can we assume the first character won't be a space?

@xnor No, I'll add a test case. Sorry.

Jelly, 14 13 bytes
nŒlTɓḲFŒlŒuṛ¦

Try it online!
How it works
nŒlTɓḲFŒlŒuṛ¦  Main link. Argument: s (string)

 Œl            Convert s to lowercase.
n              Perform character-wise "not equal" comparison.
   T           Get the indices of all truthy elements, i.e., the indices of all
               uppercase letters in s. Let's call the resulting array J.
    ɓ          Begin a dyadic chain with left argument s and right argument J.
     ḲF        Split s at spaces and flatten, removing the spaces.
       Œl      Convert s to lowercase.
            ¦  Sparse application:
         Œu        Convert s to uppercase.
           ṛ       Take the resulting items of the uppercased string at all indices
                   in J, the items of the lowercased string at all others.

C (gcc), 82 79 74 72 69 67 66 bytes
f(c){for(char*s=c,*p=c;c=*s++;c&&putchar(c^(*p++|~c/2)&32))c&=95;}

Try it online!

this will segfault if the char* doesn't fit in an int, which can be fixed for +2 bytes

Python 3, 78 75 72 bytes
s=input()
for c in s:s=s[c>' '!=print(end=(c+c).title()[s<'@'or'['<s]):]

Thanks to @xnor for golfing off 6 bytes!
Try it online!

Can you just compare s instead of s[0]?

Yes, of course. Thanks!

(c*2).title() can get you both cases, though switched.

Another 3 bytes. Thanks again!

Tricky! Took me a while to figure out that c>' '!=f() is equivalent to (c>' ') and (' '!=f()).

Breaks, if the string contains an @. Should be [s<'A'or'['<s]

Python 2, 114 bytes
x=input()
X=x.replace(' ','')
print''.join([X[i].upper()if x[i].isupper()else X[i].lower()for i in range(len(X))])

Try it online!
Equivalently:
Python 2, 114 bytes
lambda x:''.join([[str.lower,str.upper][x[i].isupper()](x.replace(' ','')[i])for i in range(len(x)-x.count(' '))])

Try it online!

''.join([(X[i].lower,X[i].upper)[x[i].isupper()]()for i in range(len(X))]) for -5 bytes.

96 bytes: x=input();print''.join([(c+c).title()[1-x[i].isupper()]for i,c in enumerate(x.replace(' ',''))])

Haskell, 98 95 89 88 81 bytes
Thanks to @name, @nimi, @Zgarb, and @Laikoni for helping shave off 14 bytes total
import Data.Char
\s->zipWith(\p->last$toLower:[toUpper|isUpper p])s$filter(>' ')s

Ungolfed:
import Data.Char
\sentence -> zipWith (\oldChar newChar ->
                        if isUpper oldChar
                        then toUpper newChar
                        else toLower newChar)
                     sentence
                     (filter (/= ' ') sentence)

On mobile, but looks like you can save some bytes with filter(/=' ')

Yep, certainly can. Missed the part of the spec noting that spaces were the only whitespace that needed removing.

filter(>' ') for one byte less

I think the body of the lambda can be shortened to last(toLower:[toUpper|isUpper p])c

Switching the arguments of zipWith should save one more byte: f s=zipWith(\p->last$toLower:[toUpper|isUpper p])s$filter(>' ')s.

I tried something cute, but it came out saving 0 bytes: f=toLower;\s->zipWith(\p->last$f:[toUpper|f p<p])s$filter(>' ')s

Python 2, 100 bytes
s=input()
print"".join([c.lower(),c.upper()][s[i].isupper()]for i,c in enumerate(s.replace(" ","")))

Welcome to PPCG, and very good first answer!

05AB1E, 15 14 bytes
-1 byte thanks to Emigna
ðKuvy¹Nè.lil}?

Try it online!
ðK             # Remove spaces
  u            # Convert to uppercase
   vy          # For each character...
     ¹Nè       #   Get the character at the same index from the original input
        .lil}  #   If it was a lowercase letter change this one to lowercase
             ? # Print without a newline

You save a byte if you uppercase the space-removed string and lowercase it in the condition.

JavaScript (ES6), 94 91 85 84 81 bytes
s=>s.replace(r=/./g,c=>1/c?"":c[`to${r<s[x]&s[x++]<{}?"Upp":"Low"}erCase`](),x=0)

6 bytes saved with assistance from ETHproductions & Arnauld.
3 bytes saved thanks to l4m2

Try it online!

Ninjad :P https://codegolf.stackexchange.com/a/128951/65836

Could you do '@'<s[i]&s[i]<'['??

@StepHen: Aw, man, didn't see that last night while I was working on this.

@ETHproductions: I was wondering if that might be shorter but I was too lazy to look up which characters I'd need to use :D Turns out it doea save a byte; thanks.

Fail but your last version work and same length

c==" " => c<"!" or even 1/c

V, 24 bytes
ÄVuÓó
ejlDò/¥2lõ
vuk~òGd

Try it online!
These kind of challenges are exactly what V was made for. :)
Explanation:
Ä           " Duplicate this line
 Vu         " Convert it to lowercase
   Óó       " Remove all spaces
e           " Move to the end of this line
 j          " Move down a line (to the original)
  l         " Move one char to the right
   D        " And delete the end of this line
    ò       " Recursively:
     /      "   Search for:
         õ  "     An uppercase character
      ¥2l   "     On line 2
            "     (This will break the loop when there are no uppercase characters left)
vu          "   Convert it to lowercase
  k         "   Move up a line
   ~        "   Convert this to uppercase also
    ò       " Endwhile
     G      " Move to the last line
      d     " And delete it

@DLosc Good questions! The newlines signal the end of a regex command, such as a substitute (remove) or search command. More detail is on this page: https://github.com/DJMcMayhem/V/wiki/Regexes

Retina, 77 71 bytes
.+
$&¶$&
T`L `l_`.+$
+`((.)*)[A-Z].*(¶(?<-2>.)*)
$1$3
.+¶

T`l `L_` .?

Try it online! Link includes test suite. Explanation: The first stage duplicates the line while the second stage lowercases the duplicate and deletes its spaces. The third stage then loops through each uppercase letter from right to left and attempts to place a space before the corresponding character on the second line. The first line is deleted and the spaces are used to uppercase the relevant characters of the result. Edit: Saved 6 bytes thanks to @Kobi.

Small question: Are the (.?) and $4 parts needed? It looks like having an optional group at the end does nothing.

@Kobi Nothing small about that question! It had originally been part of an attempt at using lookarounds to match the characters to be uppercased directly instead of having to translate them as a separate step.

Alice, 32 bytes
/..- ~l+u~mSloy
\ia''-y.'Qa.+a@/

Try it online!
Explanation
This is a standard template for programs that work entirely in ordinal mode.  Unwrapped, the program is as follows:
i.' -l.uQm.lay.a-'~y+'~aS+o@

i       take input as string
.       duplicate
' -     remove spaces from copy
l.u     create all-lowercase and all-uppercase versions
Q       reverse stack, so original string is on top
m       truncate original string to length of spaces-removed string
.lay    convert everything except uppercase characters to \n
.a-'~y  convert everything except \n (i.e., convert uppercase characters) to ~
+       superimpose with lowercase string
        \n becomes the corresponding lowercase character, and ~ remains as is
'~aS    convert ~ to \n
+       superimpose with uppercase string
        lowercase in existing string stays as is because it has a higher code point
        \n becomes corresponding uppercase character
o       output
@       terminate

Java 8, 184 177 161 bytes
s->{String r="";for(int i=0,j=i,t,u;i<s.length;){t=s[i++];if(t>32){u=s[j++];r+=(char)(t<65|t>90&t<97|t>122?t:u>64&u<91?t&~32:u>96&u<123|u<33?t|32:t);}}return r;}

Can definitely be golfed some more..
- 16 bytes thanks to @OlivierGrégoire by taking the input as char[] instead of String.
Explanation:
Try it here.
s->{                           // Method with char-array parameter and String return-type
  String r="";                 //  Result-String
  for(int i=0,j=i,t,u;         //  Some temp integers and indices
      i<s.length;){            //  Loop over the String
    t=s[i++];                  //   Take the next character and save it in `t` (as integer)
                               //   and raise index `i` by 1
    if(t>32){                  //   If `t` is not a space:
     u=s[j++];                 //   Take `u` and raise index `j` by 1
     r+=                       //   Append the result-String with:
      (char)                   //    Integer to char conversion of:
       (t<65|t>90&t<97|t>122?  //     If `t` is not a letter:
        t                      //      Simply use `t` as is
       :u>64&u<91?             //     Else if `u` is uppercase:
        t&~32                  //      Take `t` as uppercase
       :u>96&u<123|u<33?       //     Else if `u` is lowercase or a space:
        t|32                   //      Take `t` as lowercase
       :                       //     Else:
        t);                    //      Take `t` as is
    }
  }                            //  End of loop
  return r;                    //  Return result-String
}                              // End of method

Take a char[] instead of a String for this one, you'll save up plenty of bytes!

On the other hand, I answered too with another algorithm. And here, I take the opposite arguments: in = String, out = char[] :-)

Java (JDK), 84 bytes
s->{int j=0,c;for(var k:s)if((c=k&95)>0)System.out.printf("%c",c^(s[j++]|~c/2)&32);}

Try it online!
Credits :

Dennis for the bit twiddling as it's a good way to shorten the answer
Fhuvi for trimming 12 bytes.

@ceilingcat that doesn't work: Hi! Test! should become Hi!tEst!, but with your solution it becomes Hi!Test.

Python 3, 117 114 98 bytes
s=input()
i,*y=0,*s.replace(' ','').lower()
for c in y:print(end=[c,c.upper()]['@'<s[i]<'[']);i+=1

Try It Online!
Edit: 3 bytes saved by UndoneStudios.
Edit: 14 bytes saved by Unrelated String.
This is pretty much my first code golf, so it's likely to be bad, minus help from comments below!
P.S. Yes, it's dumb that defining and incrementing i saves bytes over range(len(y)). Oh well.

Python 3, 85 bytes
lambda s:''.join([c,c.upper()]['@'<b<'[']for b,c in zip(s,s.replace(' ','').lower()))

Try It Online!
This solution is entirely due to att; I'm keeping it separate because the strategy seems to me to have changed enough.

Welcome to PPCG! Nice first submission! However, complying to our site's I/O standards, your submission must either be a function of a string or take input; you cannot assume input is in a variable. Hope you enjoy your stay! :)

Thanks; edited a function in, but also saved 5 bytes in the body :D

@LukeSawczak save a ton of bytes by changing to one space for indentation, and maybe add a Try It Online! link if you want to

You can remove the space after return.

@LukeSawczak how's this? https://tio.run/##LY3JTsMwAAXv@Yq52RZRBOJWKQf2fS2bQBxKalOXYBvboYSfD6nEcaR580KfF95tD8NcG4xMalJgy77eLFubskxV1KGdNVoKRCmEqlq/0lEqVWB8pME6@nGDNaQX@1rZ1IWwNib9iHVT/eNa2ai3CqLOXXRCVEtvnexVEaJ1WRppXejyWFbDsMOMXd7YGw/2mXOA5hDDEe8cs@AEyylLzvjgnJYLPrnEcYXnmsANX9wSmZK4I3NPxwPfPLLiiR@e@f0D

@StephenS Thank you! Sorry, I deleted my comment after realizing I could both make a working TIO and save bytes by using input/print, but that's good to know.

-3 bytes?

@UndoneStudios Thanks!

shaved it down a bit more

85 bytes

@att Cool. Added as a separate solution because it's a bit more of a leap than the others, but if you'd rather just make it an answer yourself, feel free to keep it and I'll purge it from mine.

the strategy is basically the same, only using zip instead of explicit indices

@att Right, but given the smallness (as I believe) of the solution space, it doesn't take that much to be a different way of doing it. I guess I'm also thinking of the overall drift from my first attempt and the likelihood that I would ever have eventually arrived at zip. But anyway, I'm happy to leave it in.

Perl, 95 94 + 1 = 95 bytes
+1 byte penalty for -n
Save one byte by replace from s/\s//g to s/ //g
$s=$_;s/ //g;$_=lc($_);while(/(.)/gs){$p=$&;$p=uc($p)if(substr($s,$-[0],1)=~/[A-Z]/);print$p;}

Try it online!
Explanation:

Make copy of input string.

Remove all spaceses and transform string to lower case.

Then start loop over each letter. Test letter in same position in saved string for upper case. If it upper - make current letter captitalized.
Print letter.

Note that perl need to be run with "-n" command line switch

Welcome to PPCG! If you would like, you can add a link to Try It Online: https://tio.run/# (I would add it, but I don't know if this is Perl 5 or Perl 6)

I think that you need to count +1 byte for the -n flag. Other than that, this looks good! Welcome to the site! :)

@StepHen it's Perl 5, colud you add link?
I failed to run my code there in propper way.

Happy to see a new Perl golfer! I've added the TIO link to your answer and improved the formatting.

MATL, 18 bytes
kXz"@GX@)tk<?Xk]&h

Same approach as Riley's 05AB1E answer.
Try it online!

C# (.NET Core), 108 101 bytes
using System.Linq;s=>s.Replace(" ","").Select((c,i)=>s[i]>64&s[i]<91?char.ToUpper(c):char.ToLower(c))

Try it online!

7 bytes saved after realizing that the char class has static ToUpper() and ToLower() methods.

Charcoal, 33 bytes
Ａ⁰χＦＬθ¿⁼§θι Ａ⁺¹χχ¿№α§θ⁻ιχ↥§θι↧§θι

Try it online!
As I still don't know how to pass a string with whitespaces as a single input parameter into Charcoal code, I just assign in the header the test string to the Charcoal variable that represents what would be the first input (θ):
ＡA Quick Brown Fox Jumped Over The Lazy Dogθ

So the code has the same number of bytes as if the string were passed as first input.
You can see here the verbose version of the code.

I said in another answer but just in case you forget, just input as a python array with one element

I just require the input to have a trailing newline.

PHP, 181 bytes
I try get the minor numbers of bytes,this is my code:
<?php
$s=readline();
preg_match_all('/[A-Z]/',$s,$m,PREG_OFFSET_CAPTURE);
$s=strtolower(str_replace(' ','',$s));
while($d=each($m[0]))$s[$d[1][1]]=strtoupper($s[$d[1][1]]);
echo $s;

Try it online!

Instead of a Constant PREG_OFFSET_CAPTURE you can use the value 256 , $argn is a shorter variable as readline() for an input and I think ctype_upper and use of lcfirst and ucfirst will save lots of bytes with one loop and use of $$i and ternary operator

Common Lisp, 104 bytes
(defun f(s)(map'string(lambda(x y)(if(upper-case-p x)(char-upcase y)(char-downcase y)))s(remove #\  s)))

Try it online!
Unusually short for the wordy Common Lisp!
Straightforward code:
(defun f (s)                     ; receive the string as parameter
  (map 'string                   ; map the following function of two arguments
       (lambda (x y)             ; x from the original string, y from the string with removed spaces
         (if (upper-case-p x)    ; if x is uppercase
             (char-upcase y)     ; get y uppercase
             (char-downcase y))) ; else get y lowercase
       s
       (remove #\  s)))

Perl 5, 40 bytes
37 bytes of code + -F flag. (note that on old versions of Perl, you might need to add -an flags)
print$F[$i++]=~/[A-Z]/?uc:lc for/\S/g

Try it online!
Explanations:
Thanks to -F, @F contains a list of every characters of the input.
for/\S/g iterates over every non-space character of the input. We use $i to count at which iteration we are. If $F[$i++] is an uppercase character (/[A-Z]/), then we print the uppercase current character (uc), otherwise, we print it lowercase (lc). Note that uc and lc return their argument unchanged if it isn't a letter.

Previous version (less golfed: 47 bytes):
 s/ //g;s%.%$_=$&;$F[$i++]=~/[A-Z]/?uc:lc%ge

Try it online!

Google Sheets, 213 bytes
=ArrayFormula(JOIN("",IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Z]"),MID(UPPER(SUBSTITUTE(A1," ","")),ROW(OFFSET(A1,0,0,LEN(A1))),1),MID(LOWER(SUBSTITUTE(A1," ","")),ROW(OFFSET(A1,0,0,LEN(A1))),1))))

Input is in cell A1 and the formula breaks down like this:

ArrayFormula() lets us evaluate each term of ROW() independently
JOIN() concatenates all those independent results into a single string
IF(REGEXMATCH(),UPPER(),LOWER() is what makes it alternate using upper or lower case depending on what the case was at that position in the input
ROW(OFFSET()) returns an array of values 1 to A1.length that can be fed into the MID() function so we can evaluate each character in turn

Results of test cases: (It's easier to read if you click though to the larger version.)

Ruby, 80 bytes
->a{n=a.downcase.delete' '
n.size.times{|i|(?A..?Z)===a[i]&&n[i]=n[i].upcase}
n}

Try it online!

You can save a couple bytes by using n.gsub(/./){} instead of n.size.times{};n: n.gsub(/./){(?A..?Z)===a[i]?$&.upcase: $&}.

Perl, 92 bytes
$p[$i++]=$-[0]while s/[A-Z]/lc($&)/e;s/\s//g;for$c(@p){substr($_,$c,1)=~tr[a-z][A-Z]};print;

Explanation:
$p[$i++]=$-[0]while s/[A-Z]/lc($&)/e;   #get locations of caps into an array at the same time converting letters to lowercase

s/\s//g;   #delete all spaces

for$c(@p){substr($_,$c,1)=~tr[a-z][A-Z]};   #convert lowercase letters to uppercase where uppercase letters were present

print;   # print (of course) :)

Welcome to PPCG! :)

You need to add -n flag to make your answer valid. A few golfing things: s/ //g is enough (no need \s), y/a-z/A-Z/ is the same as tr[a-z][A-Z], you can use -p flag so you don't need the last print, you don't need the parenthesis in lc$&.

Charcoal, 18 bytes
⪫Ｅ⪫⪪θ ω⎇№α§θκ↥ι↧ιω

Try it online! Link is to verbose version of code. Explanation:
    θ               Input string
   ⪪                Split on spaces
  ⪫   ω             Join together
 Ｅ                  Loop over each character
          §θκ       Get character from original string
        №α          Search uppercase letters
       ⎇            If true (nonzero)
             ↥ι     Uppercase the current character
               ↧ι   Else lowercase the current character
⪫                ω  Join together
                    Implicitly print

The recent addition of StringMap shaves off a couple of bytes:
⭆⪫⪪θ ω⎇№α§θκ↥ι↧ι

⭆ is roughly equivalent to ⪫Ｅ...ω.

GNU sed, 67 + 1 = 68 bytes
+1 byte for -r flag.
:A
s/$/;/
:
s/([A-Z]);(.?)/;\l\1\u\2/
t
s/(\S);/;\1/
t
s/ ;//
/ /bA

Try it online!
Explanation
The algorithm is pretty simple:

Insert a cursor (;) at the end of the line:
:A
s/$/;/
:

If the character before the cursor is an uppercase letter, lowercase it (\l) and uppercase the character after the cursor (\u), moving the cursor to the left, and branch back to :
s/([A-Z]);(.?)/;\l\1\u\2/
t

Otherwise, if the character before the cursor is not a space, move the cursor to the left and branch back to ;:
s/(\S);/;\1/
t

Otherwise, if the cursor is preceded by a space, delete both:
s/ ;//

Finally, if there are any spaces left, branch back to :A:
/ /bA

Rust, 143 bytes
|s|str::to_lowercase(s).replace(' ',"").chars().zip(s.chars()).for_each(|(c,d)|print!("{}",if d.is_uppercase(){c.to_ascii_uppercase()}else{c}))

Try it online!
Ungolfed:
  |input: &str|
    input.to_lowercase()          // create lowercase string
         .replace(' ', "")        // remove all spaces
         .chars()                 // iterate over characters
         .zip(input.chars())      // zip with input character iterator
         .for_each(|(c, input_c)| // for each character in both strings:
           print!("{}",                  // print the following:
             if input_c.is_uppercase() { // if the input character is uppercase
               c.to_ascii_uppercase()    // `c` in uppercase
             }
             else { c }                  // else `c`
           )
         )

Go, 184 bytes
import(."strings";u"unicode")
func f(s string)string{S:=[]rune(ReplaceAll(ToLower(s)," ",""))
for i:=range s{if i<len(S)&&u.IsUpper(rune(s[i])){S[i]=u.ToUpper(S[i])}}
return string(S)}

Attempt This Online!

Noulith, 88 bytes
\s->(for(p<<-s.lower filter (!=' '))yield if(s[p[0]].is_upper)p[1].upper else p[1])join""

Try it online!

Python 3, 125, 124 bytes
lambda s:''.join(c.upper()if i in(s.find(q)for q in s if q.isupper())else c for i,c in enumerate(s.replace(' ','').lower()))

Try it online!

Python 2, 106 105 bytes
s=input()
print''.join(map(lambda(c,u):[c.lower,c.upper][u](),zip(s.replace(' ',''),map(str.isupper,s))))

Edit: save one byte via print ''.join => print''.join.
Lambda form, 99 bytes
lambda s:''.join(map(lambda(c,u):[c.lower,c.upper][u](),zip(s.replace(' ',''),map(str.isupper,s))))

SCALA, 128 chars, 128 bytes
var l=s.toLowerCase().filter(x=>x!=32)
for(i<-0 to l.size-1){if(s(i).isUpper)l=l.substring(0,i)+l(i).toUpper+l.substring(i+1)}
l

Thanks for this challenge. Try it online!

q/kdb+, 49 bytes
Solution:
{@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}

Examples:
q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"Hi! Test!"
"Hi!tEst!"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"A Quick Brown Fox Jumped Over The Lazy Dog"
"AqUickbrOwnfoxJumpEdovertHelazYdog"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"testing TESTing TeStING testing testing TESTING"
"testingtESTIngteStInGTEstingtestingtestiNG"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"TESTING... ... ... success! EUREKA???!!! maybe, don't, NOOOOO"
"TESTING.........success!eureKA???!!!maybe,don't,nooooo"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"Enter        PASSWORD ---------"
"Enterpassword---------"

q){@[a;(&)(#:[a:lower x except" "]#x)in .Q.A;upper]}"A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Z z"
"AabbCcddEeffGghhIijjKkllMmnnOoppQqrrSsttUuvvWwxxZz"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"  TEST"
"teST"

Explanation:
Find indices where input is uppercase and then apply function upper to those indices on a lowercase, space-removed version of the input string. Note that we cannot apply the function beyond the length of the string, so use take (#) to truncate the input string to length of the lowercase, space-removed version.
{@[a;where count[a:lower x except " "]#x in .Q.A;upper]} / ungolfed
{                                                      } / lambda function
 @[ ;                                           ;     ]  / apply FUNC to VAR at INDICES: @[VAR;INDICES;FUNC]
                                                 upper   / uppercase, upper["abc"] -> "ABC"
                                       x in .Q.A         / boolean list where input is in uppercase alphabet ABC..XYZ
                                      #                  / take this many elements from list on the right (ie truncate)
           count[                    ]                   / returns length of the stuff inside the brackets, count["ABC"] -> 3
                         x except " "                    / remove " " from string
                   lower                                 / lowercase, lower["ABC"] -> "abc"
                 a:                                      / save in variable a
     where                                               / returns indices where true where[101b] -> 0 2
   a                                                     / our lowercased, space-stripped input

Bonus:
After reading the answers, thought I'd try a solution where I iterate over the input, so far I've only managed a 53 byte solution:
{a{$[y in .Q.A;upper x;x]}'#:[a:lower x except" "]#x}

Swift 3.0, 199 bytes
var s="AS Ff",i=[String](),p=[Int](),j=0;for c in s.characters{if c>="A"&&c<="Z"{p.append(j)};if c != " "{i.append(String(c).lowercased())};j=j+1};for c in p{i[c]=i[c].uppercased()};print(i.joined())

Try it Online!

C, 103 bytes
i,j,c;f(char*s){for(i=j=0;c=tolower(s[j++]);)c-32&&putchar(c-32*(s[i]>64&&s[i]<91&&c>96&&c<123))&&++i;}

Try it online!

PHP, 110 bytes
$q=strtr($s=$argn,[' '=>'']);foreach(str_split($s)as$k=>$v)echo$v<lcfirst($v)?ucfirst($q[$k]):lcfirst($q[$k]);

Breakdown
$q=strtr($s=$argn,[' '=>''])

We take our input ($argn) and store it in a smaller variable because we need it later, before stripping out all the spaces with strtr
foreach(str_split($s)as$k=>$v)

We then take our original string, split it into an array of characters, and loop through each of them.
echo$v<lcfirst($v)?ucfirst($q[$k]):lcfirst($q[$k])

We check to see if the current letter is uppercase (A is less than a probably because ASCII), and echo out the corresponding letter from the space-stripped string with the appropriate case.

Jelly, 11 bytes
ŒlðḲFŒuT}¦n

Try it online!
Just a restructuring of Dennis' original solution to avoid repeating Œl.
Œl             Lowercase the input.
  ð            Make that the left argument to the following dyadic chain.
   Ḳ           Split on spaces,
    F          flatten out the splits,
     Œu        then uppercase that
       T}¦     at the indices where
Œlð       n    the lowercase doesn't equal the original.

Vyxal, 4 bytes
ȧ⇩$•

Try it Online!
Helps to have a "with capitalisation of" built-in
Explained
ȧ⇩$•
ȧ     # Remove whitespace from the input
 ⇩    # and lowercase it
  $•  # Transfer the capitalisation of the original input to the stripped input.
# The reason for `•` doing this is because on lists, `•` is mould. Therefore, the idea was that it "moulds" one string to the capitalization of the other

Created with the help of Luminespire.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to convert HEX2 to RGBA?
The world of art is full of colour, but the world of the network is even fuller than the world of art of diferent colours and it's renderings. That's why we need to know how to convert one type of colour format to another.
The challenge is self-evident:
Write a program / function than converts an given HEX code (#00ff0080, for instance) to RGBA (like rgba(0, 255, 0, 0.5)).
Rules:

External libraries/ built-ins for converting HEX to RGBA are disallowed. However, jQuery and syntax replacers like that are acceptable.
Standard Input/Output rules apply.
Format of the alpha can be between (1 == 100%) or the other (100 == 100%) that's not really important.
The output is flexible, as long as it returns the 4 converted values (as a String, Array, List, your choice).
You may choose to take the input without the # in the beginning. Hence, you can take input as either #RRGGBBAA or RRGGBBAA. You can assume that the hex code (excluding the #) will always be 8 characters long.
You should divide all the values by 255, including the alpha. The minimum decimal precision (for the alpha will be 2 decimal places).

Test Cases
Input:  00ff0080
Output: 0, 255, 0, 0.5

Scoring
code-golf, the code with the least amount of bytes wins.

Comments are not for extended discussion; this conversation has been moved to chat.

Are we required to take the "hex code" as a string? You say that we can take it without the leading #, in which case it would just be a 32-bit integer value. Is it legal to take it as that?

JavaScript (ES6), 73 54 50 bytes
(Saved some bytes thanks to @LeakyNun, the edited challenge, and @CraigAyre.)
s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))

let f=

s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))

console.log(f('00ff0080'));

Rick, it looks like we have the final spec for this now so you can update your answer.

As well as @Shaggy's comment you can save a few bytes by using eval instead of parseInt: s=>s.match(/../g).map((x,i)=>eval('0x'+x)/(i-3?1:255))

@CraigAyre, eval is a great alternative to parseInt for golfing purposes, thanks!

@RickHitchcock, no worries! You can also shave a couple of bytes from the regex using /../g. You might be able to reduce it even further using replace over match/map

Oh, I see the rules have changed, so the initial pound sign is no longer required.

Yeah, it's now optional. +2 bytes for supporting it isn't bad however!

Can't find a good replace solution that's shorter.  If you have one, you should post it – would be an interesting alternative.

@CraigAyre, found a great alternative to parseInt and eval for hexadecimal:  +('0x'+c)

@RickHitchcock, nice! You could even drop the conversion to number and divide the string directly to save another byte

Duh, of course!  : )

Japt v2.0a0, 13 10 bytes
Takes input as a string, without the leading #. Outputs the rgba value as an array.
ò mnG o÷#ÿ

Try it
ò mnG o÷#ÿ     :Implicit input of string
ò              :Partitions of length 2
  m            :Map
   n           :  Convert to integer from base
    G          :  16
      o        :Modify last element
       ÷       :  Divide by
        #ÿ     :  255

05AB1E, 9 bytes
2ôH`255/)

Try it online!
At least we have supporters like Emigna to often use some common sense...(that's what you get for golfing all day and then you start producing stuff like 2ô16öRć255/¸ìR ಠ_ಠ)

5 bytes shorter: 2ôH\žz/)`

@Emigna The challenge has been closed nevertheless...

PHP, 63 bytes
Output as array

$h=array_map(hexdec,str_split($argn,2));$h[3]/=255;print_r($h);

Try it online!
PHP, 80 bytes
Output as rgba value, Input without #

$h=array_map(hexdec,str_split($argn,2));$h[3]/=255;echo"rgba(",join(",",$h),")";

Try it online!
PHP, 88 bytes
Output as rgba value, Input with #

for(;$i<7;)$h[]=hexdec($argn[++$i].$argn[++$i]);$h[3]/=255;echo"rgba(",join(",",$h),")";

Try it online!

C (gcc), 139 bytes
C(x){x=x>57?x-87:x-48;}
#define Z C(h[i])*16+C(h[++i]))
i;f(char*h){printf("rgba(");for(i=0;i<6;i++)printf("%i, ",Z;printf("%g)",(Z/256.);}

Try it online!
My other attempt clocked in at 145 bytes. I'm not much of a C golfer, so this could probably be shorter.

Vim, 46 bytes
:s/../$((16#&)) /g␊iecho ␛$hhi*100/255␛:w !sh␊

Takes input without the # and returns by printing on the screen.

Jelly, 15 14 bytes
Øhi$€’s2ḅ⁴÷4¦⁹

Try it online!
How it Works
Øhi$€’s2ḅ⁴÷4¦⁹ - main link, takes input without # and all lowercase
   $€             - to each input character:
  i               - return its 1-based index in
Øh                - the string "0123456789abcdef"
     ’            - decrement (otherwise 0 is mapped to 1 and f to 16)
      s2          - split the characters into groups of two
        ḅ⁴        - convert from base 16 to decimal
           4¦     - on the fourth element:
          ÷       - divide by
             ⁹    - 256

-1 byte thanks to @EricTheOutgolfer

PHP, 72 bytes
Jörg´s array output version is unbeatable; but there are other options:
<?=($a=hexdec($argn))>>24,",",255&$a>>16,",",255&$a>>8,",",(255&$a)>256;

Run as pipe with -F. # does not matter, plain csv output
or 73 bytes (run with -R):
for($a=hexdec($argn);$i++<4;)echo(255&$a>>32-8*$i)/($i<4?:256),","[$i>3];

74 bytes with the spaces:
<?=($a=hexdec($argn))>>24,$c=", ",255&$a>>16,$c,255&$a>>8,$c,(255&$a)>256;

not so plain, 81 bytes:
rgba(<?=($a=hexdec($argn))>>24,$c=", ",255&$a>>16,$c,255&$a>>8,$c,(255&$a)/256?>)

Stacked, 47 45 41 bytes
[2#<$unhexmap(1::256)/', '#`'rgba(@id)'!]

Try it online!

Excel, 99 bytes
=HEX2DEC(LEFT(A1,2))&","&HEX2DEC(MID(A1,3,2))&","&HEX2DEC(MID(A1,5,2))&","&HEX2DEC(RIGHT(A1,2))/256

SmileBASIC, 50 bytes
INPUT H$RGBREAD VAL("&H"+H$)OUT R,G,B,A?R,G,B,A/#L

The hexadecimal string is converted to a number using VAL(), then RGBREAD extracts each byte. #L is a constant with the value 256.
RGBREAD is designed to extract the channels from an ARGB color, but really it just splits a 4 byte integer into 4 separate bytes, so the order doesn't matter.

I always like seeing [tag:basic] responses, but I am afraid that this response may be invalid, as it uses a built in for converting hexadecimal to rgba

I think it doesn't count as a hex->rgba builtin because it requires an extra step to convert the hex string into an integer.

Actually, looking at it again, I think you are right, the explicit conversion from hex to int would make it valid.

PowerShell Core, 73 62 bytes
$args-split'(..)'-ne''|%{"0x$_"/(1,1,1,256)[$i++]}|% *g "0.##"

-11 bytes thanks to Mazzy
Try it online!

toString is smart. regexp instead substring?

q/kdb+, 43 bytes
Solution:
{(16 sv'(.Q.n,6#.Q.a)?/:2 cut x)%1 1 1 256}

Example:
q){(16 sv'(.Q.n,6#.Q.a)?/:2 cut x)%1 1 1 256}"00ff0080"
0 255 0 0.5

Explanation:
{                                         } / anonymous lambda function
                        2 cut x             / split input into 2-char length lists
                     ?/:                    / returns index where (each-right) item is found in 'the list'
        (           )                       / 'the list'
              6#.Q.a                        / Q.a is lowercase alphabet, 6# takes first 6 chars
         .Q.n,                              / Q.n is "012..89", so prepend this onto the "abcdef"
  16 sv'                                    / converts each index from base 16 to base 10
 (                            )%1 1 1 256   / divide this output by 1,1,1,256 to get alpha in 0..1 range

JS ES2015, 84 bytes
$=>{a=[1,3,5,7].map(b=>eval("0x"+$.substr(b,2)));a[3]=(a[3]/256);return a.join(",")}

this is a function. Run it using
( CODE )("#00ff0080")

APL (Dyalog), 24 bytes
Requires ⎕IO←0 which is default on many systems. Prompts for input as uppercase without #.
256÷⍨@3⊢16⊥⍉4 2⍴⍞⍳⍨⎕D,⎕A

Try it online!
⎕D,⎕A Digits followed by Alphabet
⍞⍳⍨ prompt for text input (mnemonic: console with quote) and find the ɩndex of each letter in that
4 2⍴ reshape as four row two column matrix
⍉ transpose (because base conversion works columnwise)
16⊥ evaluate as base sixteen
⊢ yield (serves to separate 3 and 16)
256÷⍨@3 divide the 4th element by 256

Yabasic, 96 bytes
Yet another basic answer; Takes input as string and outputs to the console.
Input""a$
For i=1To 7Step 2
?Dec(Mid$(a$,i,2))/(j+1);
If i=5Then j=255Fi
If i<7Then?", ";Fi
Next

Try it online!

You can save a byte by removing the line break before ?.

Excel VBA, 90 bytes
An anonymous VBE immediate window function that takes input from the range [A1] and outputs to the VBE immediate window.
For i=1To 7Step 2:[B1]=i:?[Hex2Dec(Mid(A1,B1,2))]/IIf(i=7,256,1)&""+IIf(i<7,", ","");:Next

Batch, 150 bytes
@for /f "tokens=2-5 delims=. " %%a in ('ping/n 1 0x%1^|find "h"')do @echo/%%a,%%b,%%c&set/ay=%%d*100/255@set y=0.%y%@if %y%==0.100 set y=1@echo/%y%

Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in Batch page for ways you can golf your program

Perl 6, 42 bytes
{m:g/../.map({:16(~$_)}) »/«(1,1,1,255)}

Try it online!

Python 3, 62 bytes
lambda h:[int(h[x:x+2],16)for x in(0,2,4)]+[int(h[6:],16)/255]

Try it online!

Python 2, 54 bytes
lambda h:[int(h[i-2:i],16)/2.**(8&i)for i in(2,4,6,8)]

Try it online!