[Question]
      [
In the popular (and essential) computer science book, *An Introduction to Formal Languages and Automata* by Peter Linz, the following formal language is frequently stated:
$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$
mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".
# Challenge
Write a working program/function which gets a string, **containing "a"s and "b"s only**, as input and **returns/outputs a truth value**, saying if this string **is valid the formal language L.**
* Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.
* Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. [More info here.](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)
* Standard code golf rules apply.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Good luck!
### Truthy test cases
```
"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
```
### Falsy test cases
```
""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 85994; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}
function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
  return a.owner.display_name;
}
function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });
  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);
    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });
  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);
  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });
  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }
}
```
```
body { text-align: left !important}
#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}
#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}
table thead {
  font-weight: bold;
}
table td {
  padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">
    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">
    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÇÂs{αß
```
Only `1` is truthy in 05AB1E, and it'll output `0` (or `""` for the empty string) as falsey.
[Try it online](https://tio.run/##yy9OTMpM/f//cPvhpuLqcxsPz///PxEEkkAAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@2Hm4qrz208PP@/zv9opcQkJR2lxMQkCAWkoQwQC8YEs@EcCA/EBYkAMUQGxAATUIUQY0EkWBhiQxJUHZgNVQ4zGOoAiD6IlkQoBTEGZg7UIIhJEKMgGpKglkBtgVkDsydJKRYA).
**Explanation:**
```
Ç       # Convert the (implicit) input-string to a list of integer codepoints
        #  i.e. "aaabbb" → [97,97,97,98,98,98]
        #  i.e. "baba" → [98,97,98,97]
        #  i.e. "aab" → [97,97,98]
        #  i.e. "" → []
 Â      # Bifurcate this list (short for Duplicate & Reverse copy)
        #  STACK: [[97,97,97,98,98,98], [98,98,98,97,97,97]]
        #  STACK: [[98,97,98,97], [97,98,97,98]]
        #  STACK: [[97,97,98], [98,97,97]]
        #  STACK: [[], []]
  s     # Swap to get the duplicated list
        #  STACK: [[98,98,98,97,97,97], [97,97,97,98,98,98]]
        #  STACK: [[97,98,97,98], [98,97,98,97]]
        #  STACK: [[98,97,97], [97,97,98]]
        #  STACK: [[], []]
   {    # Sort it
        #  STACK: [[98,98,98,97,97,97], [97,97,97,98,98,98]]
        #  STACK: [[97,98,97,98], [97,97,98,98]]
        #  STACK: [[98,97,97], [97,97,98]]
        #  STACK: [[], []]
    α   # Take the absolute difference at the same positions
        #  STACK: [[1,1,1,1,1,1]]
        #  STACK: [[0,1,1,0]]
        #  STACK: [[1,0,1]]
        #  STACK: [[], []]
     ß  # And take the minimum, which will be 1 if all were truthy;
        # 0 if any were falsey; or an empty string if the list is empty
        #  STACK: [1]
        #  STACK: [0]
        #  STACK: [0]
        #  STACK: [""]
        # (after which it is output implicitly as result)
```
[Answer]
# Java 8, ~~69~~ 37 bytes
```
 s->s.matches("(a(?=a*(\\2?+b)))+\\2")
```
Regex shamelessly 'borrowed' from [here](https://stackoverflow.com/a/3644267/1682559).
-6 bytes thanks to *@Deadcode*, plus a bit more by converting Java 7 to 8
[Try it online.](https://tio.run/##PZBNb8IwDIbv/Aorp2RNI227gRiHnceF49jBCQHK2rRqTKVp4rd3cQKTIn/o9fNazgUnrC@H79m1GCN8YBN@FwBNID8e0XnYcgtg@771GMDJHY1NOEFUqyTcFilEQmocbCHAeo71WzQdkjv7KIVEuVnjk9zvXzaVVUpVqRJqXjE3XG2buDs@9c0BurT/vuHzC1CV5cd@lBOOQD7SO0YPSxBoNaLlkGJOnEuRK6s1au61TS8LTGhMLYM2KylnuYDZjad4BHNgoBAZYYYhHrHZJvsUo@JkhYlD25AUWiiVDwDY/UTynemvZIZ0HbVBPq6pxFJUAoQZ/eCR5PNr/ZBM68OJzjL9WzDun1D3v7/Nfw)
**Explanation:**
```
s->                   // Method with String parameters and boolean return-type
  s.matches("...")    //  Check if the String matches the regex explained below
```
*Regex explanation:*
```
^                   $ # (implicit by String#matches: match entire String)
                 +    # Repeat one or more times:
 (              )     #  Capture group 1, which does:
  a                   #   Match an 'a'
   (?=         )      #    With a positive look-ahead to:
      a*              #     0 or more 'a's
        (     )       #     Followed by, in capture group 2:
         \2           #      The value of capture group 2,
           ?+         #      zero or one times, giving prio to one, without backtracking
             b        #      Following by a 'b'
                  \2  # Followed by the value of capture group 2 (the 'b's)
```
[Answer]
# C (Ansi), ~~65~~ 75 Bytes
## Golfed:
```
l(b,i,j,k)char*b;{for(i=j=0;(k=b[i++])>0&k<=b[i];)j+=2*(k>97)-1;return !j;}
```
## Explanation:
Sets a value j and increments j on each b and decrements j on anything else.
Checked if the letter before is less than or equal the next letter so prevent abab from working
## Edits
Added checks for abab cases.
[Answer]
## Batch, 133 bytes
```
@if ""=="%1" exit/b1        Fail if the input is empty
@set a=%1                   Grab the input into a variable for processing
@set b=%a:ab=%              Remove all `ab` substrings
@if "%a%"=="%b%" exit/b1    Fail if we didn't remove anything
@if not %a%==a%b%b exit/b1  Fail if we removed more than one `ab`
@if ""=="%b%" exit/b0       Success if there's nothing left to check
@%0 %b%                     Rinse and repeat
```
Returns an `ERRORLEVEL` of 0 on success, 1 on failure. Batch doesn't like to do substring replacement on empty strings, so we have to check that up front; if an empty parameter was legal, line 6 wouldn't be necessary.
[Answer]
## PowerShell v2+, ~~61~~ 52 bytes
```
param($n)$x=$n.length/2;$n-and$n-match"^a{$x}b{$x}$"
```
Takes input `$n` as a string, creates `$x` as `half the length`. Constructions an `-and` Boolean comparison between `$n` and a `-match` regex operator against the regex of an equal number of `a`'s and `b`'s. Outputs Boolean `$TRUE` or `$FALSE`. The `$n-and` is there to account for `""`=`$FALSE`.
## Alternate, 35 bytes
```
$args-match'^(a)+(?<-1>b)+(?(1)c)$'
```
This uses the regex from [Leaky's answer](https://codegolf.stackexchange.com/a/86002/42963), based on .NET balancing groups, just encapsulated in the PowerShell `-match` operator. Returns the string for truthy, or empty string for falsey.
[Answer]
# Pyth - 13 bytes
```
&zqzS*/lz2"ab
```
Explained:
```
  qz          #is input equal to
          "ab #the string "ab"
     *        #multiplied by
      /lz2    #length of input / 2
    S         #and sorted?
&z            #(implicitly) print if the above is true and z is not empty
```
[Answer]
## Haskell, 39 bytes
```
p x=elem x$scanl(\s _->'a':s++"b")"ab"x
```
Usage example: `p "aabb"` -> `True`.
`scanl(\s _->'a':s++"b")"ab"x` build a list of all `["ab", "aabb", "aaabbb", ...]` with a total of `(length x)` elements. `elem` checks if `x` is in this list.
[Answer]
# Octave, 28 bytes
```
@(m)diff(+m)>=0&~sum(m-97.5)
```
This defines an anonymous function. It works also for empty input. Falsy and truthy are as described in [my MATL answer](https://codegolf.stackexchange.com/a/86018/36398).
[**Try it at ideone**](http://ideone.com/yPySIn).
### Explanation
`diff(+m)>0` checks if the input string (consisting of `'a'` and `'b'`) is sorted, that is, all characters `'a'` come before all `'b'`.
The other condition that needs to be checked is whether the numbers of characters `'a'` and `'b'` are the same. Since their ASCII codes are `97` ansd `98`, this is done subtracting `97.5` and chacking if the the sum is zero.
For empty input the result is empty, which is falsy.
[Answer]
# Mathematica ~~83~~ ~~80~~ ~~68~~ 54 bytes
```
#&@@@#<>""=="ab"&&Equal@@Length/@#&@*Split@*Characters
```
Thanks @MartinEnder for shortening it by 26 bytes :)
If input can be a list of characters instead of a string, **39 bytes** is possible:
```
#&@@@#=={a,b}&&Equal@@Length/@#&@*Split
```
eg:
```
#&@@@#=={a,b}&&Equal@@Length/@#&@*Split@{a,b,a,b,a,b}
(*False*)
```
[Answer]
# Racket, 91 bytes
```
(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr x)))(/(length x)2)))
```
Expects input in the form of a list of characters. If you really need to put it in as a raw string, that adds 21 extra characters (for **112** bytes):
```
(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr(string->list x))))(/(string-length x)2)))
```
An even longer (102 bytes with list input) way, but I think it's creative so I'm leaving it here:
```
(λ(x)(and(eqv?(/(length x)2)(length(member #\b x)))(eqv?(length(remove-duplicates(member #\b x)))1)))
```
Explanation to follow.
[Answer]
## JavaScript, 34 bytes
```
s=>(s=s.match`^a(.*)b$`[1])?f(s):1
```
In true automata fashion, this function returns 1 if it's true, and fails if it's not.
```
f=s=>(s=s.match`^a(.*)b$`[1])?f(s):1
let test_strings = ["ab", "aabb", "", "a", "abb", "abc", "abab", "abba"];
test_strings.map(s => {
try {console.log("f(\"" + s + "\") returned " + f(s));}
catch(e) {console.log("f(\"" + s + "\") threw " + e);}
});
```
[Answer]
# Excel, 55 bytes
```
=AND(A1<>"",A1=REPT("a",LEN(A1)/2)&REPT("b",LEN(A1)/2))
```
Test string in cell A1, formula above in any other cell. Generates a comparison string of the appropriate length and checks for a match. Shows TRUE or FALSE as appropriate.
[Answer]
# PHP, ~~61~~ 40 bytes
new approach inspired by [Didz´ answer](https://codegolf.stackexchange.com/questions/85994/count-of-as-and-bs-must-be-equal-did-you-get-it-computer/86300#86300): regexp with a recursive pattern
```
<?=preg_match('#^(a(?1)?b)$#',$argv[1]);
```
P.S.: I see now that I am not the first one with this pattern. You never stop learning.
---
Josh´s [C solution](https://codegolf.stackexchange.com/questions/85994/count-of-as-and-bs-must-be-equal-did-you-get-it-computer/86014#86014) translated to PHP comes at the same size (with one byte lost in translation, one byte golfed for PHP with bitwise `and`, one byte golfed for C and PHP):
`<?=strlen($s=$argv[1])==2*strspn($s,a)&$s[strrpos($s,a)+1]>a;` (61 bytes)
---
My second own approach, a little longer: build a string with (input length / 2) of `a`, one of `b` and compare the concatenation to input:
`<?=str_repeat(a,$n=strlen($s=$argv[1])/2).str_repeat(b,$n)==$s;` (63 bytes)
Could save 3 bytes on that if I could use `($r=str_repeat)` for a function call directly ... if.
---
all versions:
* take the string as argument from cli
* print `1` for true, nothing for false
---
**testing**
* replace `<?=` with `<?function f($s){return`
* remove `=$argv[1]` (or replace `$argv[1]` with `$s`)
* append `}` and my test suite (below)
* call in a web browser
```
function out($a){if(is_object($a)){foreach($a as$v)$r[]=$v;return'{'.implode(',',$r).'}';}if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',$e==$y?'Y':'N',"</td></tr>";$h='';}
$cases=[
    1=>[ab,aabb,aaabbb,aaaabbbb,aaaaabbbbb,aaaaaabbbbbb],
    0=>['',a,b,aa,ba,bb,aaa,aab,aba,abb,baa,bab,bba,bbb,aaaa,aaab,aaba,
        abaa,abab,abba,abbb,baaa,baab,baba,babb,bbaa,bbab,bbba,bbbb]
];
foreach($cases as$e=>$a)foreach($a as$x)test($x,$e,f($x)|0);
```
[Answer]
# Pyth, 7 bytes
```
.AanV_S
```
[Try it online](https://pyth.herokuapp.com/?code=.AanV_S&test_suite=1&test_suite_input=%22ab%22%0A%22aabb%22%0A%22aaabbb%22%0A%22aaaabbbb%22%0A%22aaaaabbbbb%22%0A%22aaaaaabbbbbb%22%0A%22%22%0A%22a%22%0A%22b%22%0A%22aa%22%0A%22ba%22%0A%22bb%22%0A%22aaa%22%0A%22aab%22%0A%22aba%22%0A%22abb%22%0A%22baa%22%0A%22bab%22%0A%22bba%22%0A%22bbb%22%0A%22aaaa%22%0A%22aaab%22%0A%22aaba%22%0A%22abaa%22%0A%22abab%22%0A%22abba%22%0A%22abbb%22%0A%22baaa%22%0A%22baab%22%0A%22baba%22%0A%22babb%22%0A%22bbaa%22%0A%22bbab%22%0A%22bbba%22%0A%22bbbb%22)
### How it works
```
      SQ     sorted input
     _       reverse
   nV   Q    vectorized not-equal with input
  a      Q   append input
.A           test whether all elements are truthy
```
[Answer]
## C, 65 bytes
```
m,t;C(char*c){for(m=1,t=0;*c;)m>0&*c++-97&&(m-=2),t+=m;return!t;}
```
[Answer]
## Brainfuck, 77 bytes
```
,
[
  [
    >+[>+<-]<<
    ,[>->+<<-]
    >[<<]
    >
  ]
  >+[<<]
  >
  [
    >-[>+<-]<<
    ,
    [
      [>->+<<-]
      >[<<]
      <
    ]
    >>
  ]
  +>[<]
]
<.
```
Expects input without a trailing newline. Outputs `\x00` for false and `\x01` for true.
[Try it online.](http://brainfuck.tryitonline.net/#code=LFtbPitbPis8LV08PCxbPi0-Kzw8LV0-Wzw8XT5dPitbPDxdPls-LVs-KzwtXTw8LFtbPi0-Kzw8LV0-Wzw8XTxdPj5dKz5bPF1dPC4&input=YWFhYWFhYmJiYmJi)
The idea is to increment `n` for initial `a` characters and decrement `n` for subsequent `b` characters and then check whether `n` is zero at the end, short-circuiting to print false if the input does not match `/^a+b+$/`. Since the input is guaranteed to match `/^[ab]*$/`, we can ignore the fact that `ord('a') = 97` and just use `ord('b') = ord('a') + 1` to check for `/^a+b/`.
[Answer]
# [Cubically](https://github.com/aaronryank/cubically), ~~109~~ ~~98~~ ~~70~~ 60 bytes
```
+52/1+55~=7!6&(:7UR'UF'D2~=7)6>7?6&(:7D2FU'RU'~=7)6>7!6&!8%6
```
-11 bytes thanks to TehPers
-10 bytes thanks to new language feature
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f29RI31Db1LTO1lzRTE3DyjzI0MnQx9DNECigaWZnbg8WdDP2MXYyDjKGCgJVKlqomv3/nwgCSSAAAA "Cubically – Try It Online")
Prints `1` if the string matches L, otherwise prints nothing.
Explanation:
```
+52/1+55            Sets the notepad to 97 ('a')
        ~           takes input
         =7!6&      exits if input is not 'a'
(             )6    While the notepad is truthy
 :7                 Save the current character value
   UR'UF'D2         Perform a cube operation
           ~=7      Set notepad to true if next character is the same
>7?6&               Exit if next character is end of input (-1)
(             )6    While the notepad is truthy
 :7                 Save the current character
   D2FU'RU'         Reverse one iteration of the previous operation
            ~=7     Set notepad to true if next character is the same
>7!6&               Exit if next character is NOT end of input
!8%6                Print 1 if the cube is solved
```
The looping operation has been replaced with a new sequence with a period of 1260, which will still never give a false negative but now is guaranteed to work for inputs of less than 1260 characters.
I've replaced the previous check for solved cube with `!8%6`. `8` is a recently added pseudo-face which is always equal to "Is the cube solved?" so I can just branch on that directly.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 17 bytes (16 + '-n' flag)
```
p~/^(a\g<1>?b)$/
```
[Try it online!](https://tio.run/##KypNqvz/v6BOP04jMSbdxtDOPklTRf///8TEJC4wSuICkkAaxAGCJCD4l19QkpmfV/xfNw8A "Ruby – Try It Online")
The recursive regex solution ported to ruby.
[Answer]
>
> Nearly 5 months later, decided to come back to my first answer here to see if I could golf it more. Here's the results!
>
>
>
# [Zsh](https://www.zsh.org/), 28 bytes
```
eval ${${${1:?}//a/( }//b/)}
```
Just as I posted my 29 byte answer, I thought "what about if we handle the empty case specially?" Turns out, it's one byte shorter!
[Try it online!](https://tio.run/##XY3BCoMwEETv@YqBClqohF5bwW9JzIqBYEoSW2vx29No1UNnWZZ5u8NOvouvThuCI6FgdE93KMvoKQw8BZQlsoWyYnVjXDfZZ6nrrZ45F7xAGpKf53hmVVVlNXCCHcJjCKBRBzRWEVrr0pOWHPUNXTCRs9AewQ2hezNle4oiSSaleMLEhMRPm5fi8K0wfjnYTg6wR3aQ5/@R9GHpA3wB "Zsh – Try It Online")
Successful cases: `( ( ( ... ( ( ))...)))`.
Unsuccessful cases:
* Unmatched/uneven parens: obviously fails
* `/ba/` case: `( )( )` is a "parse error" in the eval, but gives `unknown file attribute:`  if run directly.
* Empty case: `${1:?}` handles exactly this.
---
# [Zsh](https://www.zsh.org/), 29 bytes
```
eval \(${${1//a/(+}//b/+i)}\)
```
[Try it online!](https://tio.run/##XY1BCoMwFET3OcVABRUroesKvYibaL4YCKbE2FrFs6fRqosO/MW8P8NMfevfrdIES0JCq47ukIbRS2j05JDniFbKks2NfvuUSTRH841zwZNs4bzimUqXMvUpK4oiegAXmME9BwcalUNtJKExNqw0ZKmr6YqJrIHq4ezg2g@TpiMvgqqgUA@YmKjw0@4rcfpG6H4N7JETHJUDxPF/JSysd4Iv "Zsh – Try It Online")
Same "eval matching delimiters" principle, but this time using math mode instead of parameter expansions:
```
eval \(${${1//a/(+}//b/+i)}\)
     \(                    \)   # literal ( )
         ${1//a/(+}             # replace 'a' with '(+'
       ${          //b/+i)}     # replace 'b' with '+i)'
```
A successful result looks like: `((+(+(...+(++i)+...i)+i)+i))`, incrementing `i` to `1` and adding it repeatedly. This will result in a positive integer, which `(( ))` evaluates truthy.
An unsuccessful result looks like one of the following:
* Uneven/unmatched parens (obviously fails)
* `/^b(a{n}b{n})?a$/` case: `(+i)(...)(+)` fails with "missing identifier after `+`"
* Any other `/ba/` case: `(...)(...)` errors in math mode
* Empty case: `()` is an anonymous function with no body, and errors
---
>
> *Original answer:*
>
>
>
# [Zsh](https://www.zsh.org/), 35 bytes
```
eval '${'${${1//a/'${'}//b/'}'}'#}'
```
[Try it online!](https://tio.run/##qyrO@P8/tSwxR0FdpRqIVKoN9fUT9UGcWn39JH31WiBUrlX///9/YlJiEgA "Zsh – Try It Online")
([More examples](https://tio.run/##XVDLboMwELzzFauARCMlQr22UZsee8wnmDAJqMamfiSFiG@nuyFJpa6x8c6Md8cefD2l9GlorzyotzF3oLM1FVxjjqRKGwOFuvFUQzH4kqT0NCyJyHe6CZ45kG4MSM37wde01w3XiLoS8U7EFb6jDfiTC7MV5gvoPCnnVE8H61omFtllXBCMj@wFbRd68kHsiA7UOXi4E6T6hw5wRgXofkUOrT3h2mI2u@KK3JX/ylTUmI7vIrvoZ9Xetq3ks393jC0MX4ltzOIkOdeNBhdWs@iVKpt4BFqvxeXTdrfkdVgKN46LCSelKc8u/GWX56JQhSRjUZRFPvJIx3zabDbZO1FK/LJiCD9NYCcVrn0dDnAwe6xogLPEDx9cDHWfVNZgUhwlB70JjESVNMctL9UjPyjtRXCTPID7kTuQ5/@PcAeZD@AX "Zsh – Try It Online"))
Inspired by [xnor's post](https://codegolf.stackexchange.com/a/86032/86147), this outputs via exit code. Zsh will happlily handle nested `${}`s, but will err on `${${...}${...}}` or unmatched braces.
There are two caveats which makes this longer:
* We need the outer `${...}`, since `${}${}` is valid zsh.
* We need a `#` at then end, which causes an error when the input is the empty string:
	+ `${${}#}` is prefix removal, which is fine.
	+ `${#}` evaluates to the number of parameters, which will be an integer and not a valid command.
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 24 bytes
```
f('a':s++"b")=s==""||f s
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NQz1R3apYW1spSUnTttjWVkmppiZNofh/bmJmnoKtQpqCUiIYJIGB0n8A "Curry (PAKCS) – Try It Online")
Returns `True` for truth, and nothing otherwise.
[Answer]
# Python 2, ~~43~~ 40 Bytes
```
lambda s:''<s==len(s)/2*"a"+len(s)/2*"b"
```
[Try it online!](https://tio.run/##bY7LbsQgDEX3/gqLTUKrmSazpKHLfkF3aRZGSVQkhkTAqJqvTzH0samE7OvHPXi/p4/NXw573beQMN7jM6za0dXMhFFFrRsyzRYwDnE89Wp66Ya1jWOvTv0kweoO1jx1aD2bzzHN1itAu6JVuAfrUy50Xzpu8a2TSH5Gl2FThr/7RqHTbuwYCD@M7ZbOn8GmpRVv4bYoRMGA9vi9rGmGfBwTo3y6PAgSj3@FEQdK/mpxcUHxSjkpFPIfvpMHGSAyHHIsiXMVRX3Lqg0AAXfA5FdGbAfKJVNMmeRcxtVa0LzFK1QCG6qjWNjDJl4xBVM4FVRJ5gs "Python 2 – Try It Online") - considered the obvious solution thanks to *Leaky Nun*
other idea, 45 bytes:
```
lambda s:s and list(s)==sorted(len(s)/2*"ab")
```
[Try it online!](https://tio.run/##bY6xbsQgDIZ3nsJiCVS6a3IjPTr2CbqlGYxCVCSORDGn6p4@xdCqSyVk/8b@P3t75M81XY5w29Y9Az3oRSw24s3NCGTI2g5dt@5AVxpPg5le@@uiaBzMaZi0CLYXS@lGCInNZ8pzSEZAWCAY2PaQcinsUH@iTypqwDRDLLCpwD9SZyDaOPYMFL@M9Z7PX3vIXsn3/e4NgGSAOv4ua5hAWZG2lsr1fla8gfTz5Umik/oAzft8JA/yDUsyIPU/S6I@0AlEx6HEmjg3UdWPbNoJgYJ/hCuvttgusJRMcbVTcm03a0XzFI9gDWxojmphD5t4xFVM5TRQI7lv "Python 2 – Try It Online")
*-4 bytes by using len/2 (i get an error when the half comes last)*
*now gives false for the empty string*
*-3 bytes thanks to xnor*
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ṡ=s`abdcạ&
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboW6x7uXGBbnJCYlJL8cNdCtSXFScnFUKkFaxLBIAkMIGIA)
#### Explanation
```
Ṡ=s`abdcạ&  # Implicit input
Ṡ=          # Is the input sorted?
  s         # Swap so the input is back on top
   `ab      # Push the string "ab"
      dc    # Count the occurrences of "a" and "b"
        ạ   # Are they equal to each other?
         &  # Logical AND
            # Implicit output
```
[Answer]
## Pyke, 10 bytes
```
le"ab"*Sq&
```
[Try it here!](http://pyke.catbus.co.uk/?code=le%22ab%22%2aSq%26&input=ab)
Or 9 bytes if null input isn't valid
```
le"ab"*Sq
```
[Answer]
# Ruby, 33 bytes
[Try it online](https://repl.it/CeXK)
```
->s{s==?a*(l=s.size/2)+?b*l&&l>0}
```
[Answer]
## Actually, 14 bytes
```
"[]""ab"(t≡#ÆY
```
This uses the same strategy as [xnor's solution](https://codegolf.stackexchange.com/a/86032/4372) for the first part: transform the input into a nested iterable.
[Try it online!](http://actually.tryitonline.net/#code=IltdIiJhYiIodOKJoSPDhlk&input=ImFhYmIi)
Explanation:
```
"[]""ab"(t≡#ÆY
"[]""ab"(t      translate "a" -> "[", "b" -> "]"
          ≡     eval (since this is evaluating a literal, it still works in the online interpreter) - leaves a list if the string is valid, else a string
           #    listify (does nothing to a list, makes a list of characters for a string)
            Æ   filter strings (take all string elements in the list - so an empty list if there are none)
             Y  boolean negate (an empty list is falsey and a non-empty list is truthy, so negation gets the correct value)
```
[Answer]
# Ruby, 31 bytes
Aw, that poor syntax highlighter :)
```
->s{s=~/^a+/&&$&.tr(?a,?b)==$'}
```
Does `s` begin with one or more `a`? Is also that bunch of `a`s (`$&`) the same as the rest of the string (`$'`) if we replace all those `a`s with `b`s?
[test here](https://repl.it/Ce9w)
[Answer]
# C#, 78 67 bytes
```
bool f(string s)=>Regex.IsMatch(s,"^(?'o'a)+(?'-o'b)+(?(o)(?!))$");
```
This implementation uses .NET Regex's ["Balancing Group Definitions"](https://msdn.microsoft.com/en-us/library/bs2twtah(v=vs.110).aspx#balancing_group_definition) to match the same number of 'a' and 'b' characters while ensuring that the input isn't an empty string by using the `+` quantifier.
[Answer]
# Python, 101 bytes
```
def q(s):
 a=len(s)/2
 for x in range(a):
  if s[x]!='a' or s[a+x]!='b' or a*2!=len(s):a=0
return a
```
Not the most efficient, had some trouble with 0 being even. Could probably get it lower with python tricks.
Returns 0 if false, a positive integer if true. (which will be half len(s))
[Answer]
# k (21 bytes)
Can probably be shorter
```
{|/0,(=).(#:'=x)"ab"}
```
Example
```
k){|/0,(=).(#:'=x)"ab"}""
0b
k){|/0,(=).(#:'=x)"ab"}"ab"
1b
k){|/0,(=).(#:'=x)"ab"}"aab"
0b
```
[Answer]
# PHP bounty version, 31 bytes
for PHP 4.1, call `php-cgi -f <scriptname> s=<argument>` (or in browser with `?s=<argument>`)
for current PHP, use `$_GET[s]` instead of `$s`
---
**31 bytes**
```
<?eval(strtr("do$s;",ab,'{}'));
```
`unexpected ';'` for valid, `unexpected end of file` or `unexpected '}'` for invalid
```
<?eval(strtr("1|$s;",ab,'[]'));
```
ok for valid, `unexpected ';'` or `unexpected ']'` for invalid
# 26 bytes
if empty input was undefined or valid:
```
<?eval(strtr($s,ab,'{}'));
```
**29 bytes**, if empty input was undefined or valid:
```
<?eval(strtr("$s;",ab,'[]'));
```
Abusing other control structures:
**32 bytes**
```
<?eval(strtr("$c=$s;",ab,'[]'));
```
ok for valid, Parse error for invalid: `unexpected ';'`, `unexpected ']'` or `Cannot use [] for reading` (for `abab`)
**33 bytes**
```
<?eval(strtr("1 or$s;",ab,'[]'));
```
same as `1|`
```
<?eval(strtr("if(0)$s",ab,'{}'));
```
ok for valid, `unexpected end of file` or `unexpected '}'` for invalid input
**35 bytes**:
```
<?eval(strtr("for(;;)$s",ab,'{}'));
```
infinite loop for valid (use `for(;0;)` to make finite), same as `if` for invalid
**36 bytes**
```
<?eval(strtr("while(0)$s",ab,'{}'));
```
same as `if`
**39 bytes**
```
<?eval(strtr("function()$s;",ab,'{}'));
```
`unexpected ';'` for empty, same as `if` for other input
]


[Question]
      [
A binary recurrence sequence is a recursively-defined sequence of the following form:
$$F(1) = a\_1 \\ \vdots \\ F(y) = a\_y \\
F(n) = \alpha F(n-x) + \beta F(n-y), n > y$$
This is a generalization of the Fibonacci (\$x = 1, y = 2, a = [1, 1], \alpha = 1, \beta = 1\$) sequence and the Lucas (\$x = 1, y = 2, a = [2, 1], \alpha = 1, \beta = 1\$) sequence.
## The Challenge
Given \$n, x, y, a, \alpha\$, and \$\beta\$, in any reasonable format, output the \$n\$th term of the corresponding binary recurrence sequence.
## Rules
* You may choose for the sequence to be either 1-indexed or 0-indexed, but your choice must be consistent across all inputs, and you must make note of your choice in your answer.
* You may assume that no invalid inputs would be given (such as a sequence that terminates prior to \$n\$, or a sequence that references undefined terms, like \$F(-1)\$ or \$F(k)\$ where \$k > n\$). As a result of this, \$x\$ and \$y\$ will always be positive.
* The inputs and outputs will always be integers, within the boundaries of your language's natural integer type. If your language has unbounded integers, the inputs and outputs will be within the range \$[-2^{31}, 2^{31}-1]\$ (i.e. the range for a 32-bit signed two's complement integer).
* \$a\$ will always contain exactly \$y\$ values (as per the definition).
## Test Cases
Note: all test cases are 0-indexed.
```
x = 1, y = 2, a = [1, 1], alpha = 1, beta = 1, n = 6 => 13
x = 1, y = 2, a = [2, 1], alpha = 1, beta = 1, n = 8 => 47
x = 3, y = 5, a = [2, 3, 5, 7, 11], alpha = 2, beta = 3, n = 8 => 53
x = 1, y = 3, a = [-5, 2, 3], alpha = 1, beta = 2, n = 10 => -67
x = 5, y = 7, a = [-5, 2, 3, -7, -8, 1, -9], alpha = -10, beta = -7, n = 10 => 39
```

[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁴Cịæ.⁵ṭµ¡⁶ị
```
**Try it online!** [1](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzEsIDFd+WzEsIDJd+WzEsIDFd+Nw) | [2](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzIsIDFd+WzEsIDJd+WzEsIDFd+OQ) | [3](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzIsIDMsIDUsIDcsIDExXQ+WzMsIDVd+WzIsIDNd+OQ) | [4](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=Wy01LCAyLCAzXQ+WzEsIDNd+WzEsIDJd+MTE) | [5](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=Wy01LCAyLCAzLCAtNywgLTgsIDEsIC05XQ+WzUsIDdd+Wy0xMCwgLTdd+MTE)
### How it works
```
⁴Cịæ.⁵ṭµ¡⁶ị  Main link. Arguments: a; [x, y]; [α, β]; n (1-based)
       µ     Combine the links to the left into a chain.
        ¡    Execute that chain n times, updating a after each execution.
⁴              Yield [x, y].
 C             Complement; yield [1 - x, 1 - y].
  ị            Retrieve the elements of a at those indices.
               Indexing is 1-based and modular in Jelly, so this retrieves
               [a[-x], a[-y]] (Python syntax).
     ⁵         Yield [α, β].
   æ.          Take the dot product of [a[-x], a[-y]] and [α, β].
         ⁶   Yield n.
          ị  Retrieve the element of a at index n.
```
[Answer]
## Python 2, 62 bytes
```
x,y,l,a,b=input();f=lambda n:l[n]if n<y else a*f(n-x)+b*f(n-y)
```
A direct recursive solution. All inputs are taken from STDIN except for `n` as a function argument, a split that's is [allowed by default](http://meta.codegolf.stackexchange.com/a/5415/20260) (though contentiously).
There doesn't seem to be a way to save bytes with `and/or` in place of `if/else` because `l[n]` could be falsey as 0.
[Answer]
## JavaScript (ES6), ~~51~~ 44 bytes
```
(x,y,z,a,b)=>g=n=>n<y?z[n]:a*g(n-x)+b*g(n-y)
```
Note that the function is partially curried, e.g. `f(1,2,[1,1],1,1)(8)` returns 34. It would cost 2 bytes to make the intermediate functions independent of each other (currently only the last generated function works correctly).
Edit: Saved 7 bytes thanks to @Mego pointing out that I'd overlooked that the the passed-in array always contains the first `y` elements of the result.
[Answer]
## Haskell, ~~54~~ 48 bytes
```
l@(x,y,a,p,q)%n|n<y=a!!n|k<-(n-)=p*l%k x+q*l%k y
```
[Answer]
# Python 2, 59 bytes
```
x,y,A,a,b,n=input()
exec'A+=a*A[-x]+b*A[-y],;'*n
print A[n]
```
Test it on [Ideone](http://ideone.com/4Qun1t).
[Answer]
# J, 43 bytes
```
{:{](],(2>@{[)+/ .*]{~1-@>@{[)^:(3>@{[)>@{.
```
Given an initial sequence of terms *A*, computes the next term *n* times using the parameters of *x*, *y*, *α*, and *β*. Afterwards, it selects the *nth* term in the extended sequence and outputs it as the result.
## Usage
Since J only supports 1 or 2 arguments, I group up all the parameters as a list of boxed lists. The initial seed values *A* are first, followed by the parameters of *x* and *y* as a list, followed by the parameters of *α* and *β* as a list, and ending with the value *n*.
```
   f =: {:{](],(2>@{[)+/ .*]{~1-@>@{[)^:(3>@{[)>@{.
   2 3 5 7 11;3 5;2 3;8
┌──────────┬───┬───┬─┐
│2 3 5 7 11│3 5│2 3│8│
└──────────┴───┴───┴─┘
   f 2 3 5 7 11;3 5;2 3;8
53
   f _5 2 3 _7 _8 1 _9;5 7;_10 _7;10
39
```
]


[Question]
      [
**GolfScript** automatically coerces values, according to the following ‘priority’ sequence:
>
> integer → array → string → block
>
>
>
(listed from lowest to highest.)
This means that `"1"7+` leaves the string `"17"` on the stack (and not `8`), because strings have a higher priority than integers.
[*To those GolfScript veterans – apologies for insulting your respective intelligences.*]
How would it be possible to do this the other way? That is, to **coerce a string into an integer**?

[Answer]
There's an operator `~` in golfscript, which does the following: `bitwise not, dump, eval`.
Therefore, `"1"` will give the string `"1"` while `"1"~` will evaluate that string (into the integer `1`).
Then, all you need to do is `"1"~7+`.
[Try it online!](http://golfscript.tryitonline.net/#code=IjEifjcr&input=)
]


[Question]
      [
Output the **current time of day** as [Swatch Internet Time](https://en.wikipedia.org/wiki/Swatch_Internet_Time).
Specifically, output a three-digit (zero-padded) number of "[.beats](https://en.wikipedia.org/wiki/Swatch_Internet_Time#Beats)" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").
For example, if the current time in UTC is `23:47`, then it is `00:47` in UTC+1 ("Biel Meantime"), and the output would be `032`.
**Examples**:
```
UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651
```
The program should produce this output then immediately exit.
Output is to standard output (or equivalent). **Must be a complete, runnable program, not a function.** The program takes no input; it outputs the *current* time.

[Answer]
# PHP, 12 bytes
```
<?=@date(B);
```
But it can only be so short because PHP has built-in Swatch Internet Time support. So this answer isn't much fun.
---
`<?=` exits HTML mode and evaluates an expression, then echoes it.
`@` silences an error.
`date()` outputs the current time, formatting it with a given format string.
`B` is an undefined constant. In PHP, if you reference a constant that doesn't exist, you get back a string containing its name, and it also produces a “notice”-level error. Here, the `@` suppresses that error. `B` is the `date()` format code for Swatch Internet Time.
`;` terminates the expression.
---
If we assume PHP is being run with the default error-reporting settings, where “notices” are silenced, we could skip the `@`, and it would only be 11 bytes.
[Answer]
# C, *56 bytes*
```
main(){printf("%03d",(int)((time(0)+3600)%86400/86.4));}
```
Explanation:
* **%03d** - tells printf to zero-pad up to 3 digits.
* **time(NULL)+3600** - gets amount of seconds (UTC) elapsed since epoch and adds an hour to it (UTC+1).
* **%86400** - divides epoch by the amount of seconds in a 24hr day and gets the remainder (representing seconds elapsed, so far, "today").
* **/86.4** - divide remaining seconds by 86.4 to get the ".beat" count since midnight (UTC+1).
### Compile (MSVC):
C:> cl swatch.c
### Compile (GCC):
$ gcc swatch.c
[Answer]
# PHP, ~~48~~ 46 bytes
```
<?=sprintf("%03d",((time()+3600)%86400)/86.4);
```
I have another PHP answer above, but this one avoids using PHP's built-in Swatch Internet Time support, so it's more interesting, if longer.
This is largely self-explanatory if you're familiar with UNIX time and `sprintf`, ~~though note I'm using `|0` as a short way to truncate a float to an integer~~ (actually I realised this is unnecessary in PHP, oops!)
[Answer]
# Java 8, 143 bytes
```
import java.time.*;interface A{static void main(String[]a){System.out.format("%03.0f",LocalTime.now(ZoneId.of("UT+1")).toSecondOfDay()/86.4);}}
```
this uses Java 8's java.time package to get current time, convert it to UTC+1, and then get the number of seconds. At the end it divides by the number of 1000s of seconds in a day, which turns out to be 86.4.
Funny how the function that actually calculates the time is only about a third of the overall program size.
[Answer]
# 05AB1E, ~~29~~ 21 bytes
```
ža>60©%®*žb+₄*1440÷Dg3s-Å0š˜J
```
After compressing integers thanks to @KevinCruijssen (-8 bytes) :
```
ža>60©%®*žb+₄*Ž5¦÷₄+¦
```
Explanation:
```
ža>60©%®*žb+₄*1440÷Dg3s-Å0š˜J
ža                               push current hours in UT
  >                              increment
   60©                           push 60 and save in register c
      %                          hours mod 60
       ®*                        push from register c and Multiply
         žb+                     add current minutes
            ₄*                   multiply by 1000
              1440÷              Integer division with 1440
                   D             Duplicate
                    g            Length
                     3s-         3-length
                        Å0       create list of a 0s
                          š      Prepand
                           ˜J    Flat and joon
```
I didn't find a better idea for prepanding Zeros, so if anyone got a better idea I'll be glad to know :)
[Try it online!](https://tio.run/##ATEAzv9vc2FiaWX//8W@YT42MMKpJcKuKsW@YivigoQqMTQ0MMO3RGczcy3DhTDFocucSv//)
[Try the 21 bytes online!](https://tio.run/##yy9OTMpM/f//6L5EOzODQytVD63TOrovSftRU4vW0b2mh5Yd3g5kah9a9v8/AA)
[Answer]
# Javascript, ~~53~~ ~~52~~ 48 bytes
```
alert((new Date/864e5%1+1/24+'0000').slice(2,5))
```
Explanation:
`new Date/864e5%1` is the fraction of a day in UTC. `+1/24` adds 1/24th of a day (1 hour), moving it to UTC+1.
`"0000"` is concatenated with this, turning it into a string. Then the 3rd through 5th characters are taken. The reason `"0000"` is concatenated instead of an empty string is for the cases in which there are fewer than 3 decimal places:
* `"0.XXX`(any number of digits here)`0000"` Swatch time is XXX
* `"0.XX0000"` Swatch time is XX0
* `"0.X0000"` Swatch time is X00
* `"00000"` Swatch time is 000
(the first character is 1 instead of 0 from 23:00 UTC to 24:00 UTC, but the first character is ignored.)
[Answer]
# JavaScript, 98 bytes
```
d=new Date();t=;console.log(Math.floor((360*d.getHours()+60*d.getMinutes()+d.getSeconds())/86.4));
```
Definitely could be optimized, I had some problems with the `Date` object so I'm looking into shorter ways to do that.
[Answer]
# Octave, 64 bytes
```
t=gmtime(time);sprintf("%03.f",(mod(++t.hour,24)*60+t.min)/1.44)
```
Uses [veganaiZe's](https://codegolf.stackexchange.com/a/85107/42892) `printf` formatting.
I'm having a bit of difficulty with the time that ideone is returning, so here's a sample run with the time struct returned by `gmtime` for reference. I'll look around and see if I can get any of the other online Octave compilers to give me proper time.
```
t =
  scalar structure containing the fields:
    usec =  528182
    sec =  17
    min =  24
    hour =  21
    mday =  15
    mon =  6
    year =  116
    wday =  5
    yday =  196
    isdst = 0
    zone = UTC
ans = 933
```
[Answer]
# q/k (21 bytes)
```
7h$1e3*(.z.n+0D01)%1D
```
[Answer]
# Python 2.7, ~~131~~ ~~128~~ 121 bytes:
```
from datetime import*;S=lambda f:int(datetime.utcnow().strftime(f));print'%03.0f'%(((S('%H')+1%24)*3600+S('%M')*60)/86.4)
```
A full program that outputs the Swatch Internet Time.
Simply uses Python's built in `datetime` module to first get the `UTC+0` time in hours and minutes using `datetime.utfnow().strftime('%H')` and `datetime.utfnow().strftime('%M')`, respectively. Then, the time is converted into `UTC+1` by adding `1` to the hours and then modding the sum by `24` to ensure the result is in the 24-hour range. Finally, the hour is turned into its equivalent in seconds, which is added to the minute's equivalent in seconds, and the resulting sum is divided by `86.4`, as there are `86.4` seconds or `1 min. 24 sec.` in 1 ".beat", after which, using string formatting, the quotient is rounded to the nearest integer and padded with zeroes until the length is `3`.
---
However, I am not the one to stop here. In the above solution, I used a more direct method to convert the time to `UTC+1`. However, wanted to add a bit of a bigger challenge for myself and implement this using *only* Python's built in `time` module, which apparently does *not* have any built-in method that I know of to convert local time into `UTC+0` time. So now, without further ado, here is the perfectly working version using *only* the time module, currently standing at **125 bytes**:
```
from time import*;I=lambda g:int(strftime(g));print'%03.0f'%((((I('%H')+1-daylight)%24*3600+timezone)%86400+I('%M')*60)/86.4)
```
This can output the correct Swatch Internet Time for *any and all* time zones, and basically does pretty much everything the same as in the first solution, except this time converts the local time into `UTC+1` by first adding `1` to the hour, and then subtracting `1` if daylight-savings time is currently, locally observed, or `0` otherwise. Then, this difference is modded by `24` to ensure that the result stays within the `24` hour range, after which it is multiplied by `3600` for conversion into seconds. This product is then added to the result from the built-in `timezone` method, which returns the local offset from `UTC+0`. After this, you finally have your hours in `UTC+1`. This then continues on from here as in the first solution.
[Answer]
# Javascript, 83 bytes
```
a=(((36e5+(+new Date()))%864e5)/864e2).toFixed(),alert("00".slice(Math.log10(a))+a)
```
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 34 bytes
Update: I shouldn't code hungry. My previous answer was shorter, but didn't cast to int or left-pad. These are now fixed, with +8 bytes to left-pad (probably improvable), +1 to int cast, and -2 to optimizations. My old comment no longer applies.
```
r':/~\~)24md60*@~+1.44/i"%03d"e%o;
```
[Try it online](https://tio.run/##S85KzP3/v0jdSr8upk7TyCQ3xcxAy6FO21DPxEQ/U0nVwDhFKVU13/r/fyNjKxNzAA)
Explanation:
```
r                   read input
 ':/                split on :
    ~               unwrap array
     \~             evaluate hour to numbers
       )            increment hour
        24md        modulo 24
            60*     multiply by 60
               @~   switch to minute and eval to num
+                   add hour*60 and minute
 1.44/              divide by 1.44 to get SIT
      i             cast to int
       "%03d"e%     format as 3 leading 0s
               o;   output and discard spare 0 from modulo
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~27 23 19~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Kj z86400 s t3n
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=S2ogejg2NDAwIHMgdDNu)
Javascript port.
I hope I've done it correctly.
-4 bytes from Shaggy.
-4 more bytes from Shaggy.
-4 more more bytes from Shaggy.
[Answer]
# [Python 3](https://docs.python.org/3/), 64 bytes
```
import time
t=time.gmtime()
print(int(-~t[3]%24/.024+t[4]/1.44))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVq8QWROml54IoDU2ugqLMvBINENatK4k2jlU1MtHXMzAy0S6JNonVN9QzMdHU/P8fAA "Python 3 – Try It Online")
[Answer]
# C#, 112 bytes
```
class P{static void M(){System.Console.Write((int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4));}}
```
---
# C#, 68 bytes
```
()=>(int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4);
```
A simple port of @veganaiZe's code. Thanks to him :)
[Try it online!](https://dotnetfiddle.net/7yE0Lz)
[Answer]
## Common Lisp (Lispworks), 144 bytes
```
(defun f(s)(let*((d(split-sequence":"s))(h(parse-integer(first d)))(m(parse-integer(second d))))(round(/(+(*(mod(1+ h) 24)3600)(* m 60))86.4))))
```
ungolfed:
```
    (defun f (s)
      (let* ((d (split-sequence ":" s))
             (h (parse-integer (first d)))
             (m (parse-integer (second d))))
        (round
         (/
          (+
           (*
            (mod (1+ h) 24)
            3600)
           (* m 60))
          86.4))))
```
usage:
```
CL-USER 2759 > (f "23:47")
33
-0.36111111111111427
```
]


[Question]
      [
Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition:
**Every new string should contains the letters at the same index of the others strings**
For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on.
Examples (the numbers under the letters are the indexes of the strings):
```
input: "car", "dog", "man", "yay"
        012    012    012    012
output: "cdmy", "aoaa", "rgny"
         0000    1111    2222
input: "money", "taken", "trust"
        01234    01234    01234
output: "mtt", "oar", "nku", "ees", "ynt"
         000    111    222    333    444
```
Assume that the input is correct everytime
Shortest bytes' code wins!
**Edit:**
Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding!
**Re-Edit:**
Thanks to user [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) I inserted a snippet for the leaderboards.
```
var QUESTION_ID=85255,OVERRIDE_USER=56179;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

[Answer]
## Pyth, 1 byte
```
C
```
[Try it here](http://pyth.herokuapp.com/?code=C&input=%22car%22%2C+%22dog%22%2C+%22man%22%2C+%22yay%22&debug=0)
Another transpose builtin
[Answer]
# Python, ~~36~~ 29 bytes
`zip(*s)` returns a list of tuples of each character, transposed.
```
lambda s:map(''.join,zip(*s))
```
[**Try it online**](https://repl.it/CbMM/1)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 1 byte
```
Z
```
[Try it online!](http://jelly.tryitonline.net/#code=WgrDh-KCrEc&input=&args=WyJjYXIiLCAiZG9nIiwgIm1hbiIsICJ5YXkiXSwgWyJtb25leSIsICJ0YWtlbiIsICJ0cnVzdCJd)
[Answer]
# Vim, ~~37~~ 36 keystrokes
All the other answers are boring, and using boring single-byte builtins. Here's a hacky answer that does the entire thing manually, in something that isn't even a programming language:
```
Gmaqqgg:s/./&<cr>d<C-v>`aGo<esc>pvGgJ@qq@q`adgg
```
Explanation:
```
G                                   "move to the end of this line
     ma                             "And leave mark 'a' here
       qq                           "Start recording in register 'q'
         gg                         "Move to the beginning
           :s/./&<cr>               "Assert that there is atleast one character on this line
                      d             "Delete
                       <C-v>        "Blockwise
                            `a      "Until mark 'a'
    G                               "Move to the end of the buffer
     o<esc>                         "Open a newline below us
           p                        "And paste what we deleted
            vG                      "Visually select everything until the end
              gJ                    "And join these without spaces
                @q                  "Call macro 'q'. The first time, this will do nothing,
                                    "The second time, it will cause recursion.
                  q                 "Stop recording
                   @q               "Call macro 'q' to start it all
```
Now, everything is good, but the buffer has some extra text left over. So we must:
```
`a                              "Move to mark 'a'
  dgg                           "And delete everything until the first line
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 1 byte
```
!
```
[**Try it online!**](http://matl.tryitonline.net/#code=IQ&input=WydjYXInOyAnZG9nJzsgJ21hbic7ICd5YXknXQ)
Takes input implicitly, transposes, displays output implicitly.
[Answer]
## PowerShell v2+, ~~66~~ 54 bytes
```
param($n)for($x=0;$n[0][$x];$x++){-join($n|%{$_[$x]})}
```
Yo ... no `map`, no `zip`, no `transpose`, etc., so we get to roll our own. Big props to [@DarthTwon](https://codegolf.stackexchange.com/users/56063/darth-twon) for the 12-byte golf.
Takes input `$n`, sets up a `for` loop. Initialization sets `$x` to `0`, the test is whether we still have letters in our word `$n[0][$x]`, and we increment `$x++` each iteration.
Inside the loop, we take our array of strings, pipe it to an inner loop that spits out the appropriate character from each word. That is encapsulated in a `-join` to form a string, and that string is left on the pipeline. At end of execution, the strings on the pipeline are implicitly printed.
```
PS C:\Tools\Scripts\golfing> .\convert-n-strings.ps1 "Darth","-Twon","Rocks"
D-R
aTo
rwc
tok
hns
```
[Answer]
## CJam, ~~6~~ 5 bytes
*Saved 1 byte thanks to Luis Mendo.*
```
qS%zp
```
[Try it online!](http://cjam.aditsu.net/#code=q%20%20%20%20%20%20e%23%20Get%20all%20input%0A%20S%25%20%20%20%20e%23%20Split%20it%20on%20spaces%0A%20%20%20z%20%20%20e%23%20Take%20the%20transpose%0A%20%20%20%20p%20%20e%23%20Print%20it%20as%20an%20array&input=car%20man%20dog%20yay)
```
q      e# Get all input
 S%    e# Split it on spaces
   z   e# Take the transpose
    p  e# Print it as an array
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~45~~ 43 bytes
Byte count assumes ISO 8859-1 encoding.
```
O$#`.(?<=(.+))|¶
$.1
!`(?<=(¶)+.*)(?<-1>.)+
```
The leading linefeed is significant. Input and output are linefeed-terminated lists of printable ASCII strings (note that both have a single trailing linefeed).
[Try it online!](http://retina.tryitonline.net/#code=TyQjYC4oPzw9KC4rKSl8wrYKJC4xCiFgKD88PSjCtikrLiopKD88LTE-Likr&input=YWJjZGUKZmdoaWoKa2xtbm8K)
I knew for a while that transposing rectangular blocks would be a pain in Retina (whereas transposing squares isn't too bad), but never actually tried. The first solution was indeed a whopping 110 bytes long, but after several substantial changes in the approach, the resulting 45 bytes are by far not as bad as I suspected (but still...). Explanation will follow tomorrow.
### Explanation
**Stage 1: Sort**
```
O$#`.(?<=(.+))|¶
$.1
```
This does the main work of reordering the characters in the input, but it ends up messing up the separation into lines. Interestingly, if we remove the `|¶`, we get the code required to transpose a square input.
Sort stages (denoted by the `O`) work like this: they find all matches of the given regex (the thing after the ```), and then sort those matches and reinsert them into the places where the matches were found. As it happens, this regex matches every single character: non-linefeeds via the `.(?<=(.*))` alternative and linefeeds via the `¶`. Hence, it sorts all characters in the input. The more interesting part is what they are sorted *by*.
The `$` option activates a "sort-by" mode, where each match is replaced with the substitution pattern on the second line, which is then used for comparing the matches. Furthermore, the `#` tells Retina to convert the result of the substitution to an integer, and compare those integers (instead of treating them as strings).
So finally, we need to look at the regex and the substitution. If the first alternative matches (i.e. we have matched any character within one of the lines), then the `(?<=(.*))` captures everything up to that character on that line into group `1`. The `$.1` in the substitution pattern replaces this with the *length* of group `1`. Hence, the first character in each string becomes `1`, the second becomes `2`, the third becomes `3` and so on. It should be clear now how this transposes a square input: all the first characters of the lines come first and all end up in the top-most line, then all the second characters end up in the second line and so on. But for these rectangular inputs, we're also matching the linefeeds. Since group `1` is unused in this case, the substitution is empty, but for the purposes of the `#` option, this is considered `0`. That means, all the linefeeds are sorted to the front.
So now we do have the characters in the first order (first character of each string, second character of each string, etc.) and all the linefeeds at the start.
**Stage 2: Match**
```
!`(?<=(¶)+.*)(?<-1>.)+
```
We now need to split up the characters into lines of the correct length. This length corresponds to the number of lines in the original input, which is corresponds to the number of linefeeds we have at the beginning of the string.
The splitting is done here with the help of a match stage, which simply finds all matches of the given regex and uses the `!` option to print those matches (the default would be to count them instead). So the goal of the regex is to match one line at a time.
We start by "counting" the number with the lookbehind `(?<=(¶)*.*)`. It generates one capture in group `1` for every linefeed at the front.
Then, for each of those captures, we match a single character with `(?<-1>.)+`.
[Answer]
## Pyke, 1 byte
```
,
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2C&input=%22money%22%2C+%22taken%22%2C+%22trust%22)
Transpose.
[Answer]
# x86 machine code, 19 bytes
In hex:
```
fc89d35651a401dee2fb91aa595e464a75f1c3
```
Input: `ECX`: # of strings (n), `EDX`: individual string length (m), `ESI`: array of input strings, `EDI`: output buffer receiving array of strings. Array is presumed to be defined as `char src[n][m+1]` for input and `char dst[m][n+1]` for output, and all strings are NULL-terminated.
```
0:  fc                  cld
1:  89 d3               mov ebx,edx   ;EDX is the counter for the outer loop
_outer:
3:  56                  push esi
4:  51                  push ecx
_inner:
5:  a4                  movsb         ;[EDI++]=[ESI++]
6:  01 de               add esi,ebx   ;Same char, next string
8:  e2 fb               loop _inner   ;--ECX==0 => break
a:  91                  xchg eax,ecx  ;EAX=0
b:  aa                  stosb         ;NULL-terminate just completed string
c:  59                  pop ecx
d:  5e                  pop esi       ;First string,
e:  46                  inc esi       ;...next char
f:  4a                  dec edx
10: 75 f1               jnz _outer
12: c3                  ret
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
z:ca.
```
Expects a list of strings as input, e.g. `run_from_atom('z:ca.',["money":"taken":"trust"],Output).`
### Explanation
```
z       Zip the strings in the Input list
 :ca.   output is the application of concatenation to each element of the zip
```
[Answer]
## 05AB1E, 3 bytes
```
ø€J
```
**Explained**
```
     # implicit input, eg: ['car', 'dog', 'man', 'yay']
ø    # zip, producing [['c', 'd', 'm', 'y'], ['a', 'o', 'a', 'a'], ['r', 'g', 'n', 'y']]
 €J  # map join, resulting in ['cdmy', 'aoaa', 'rgny']
```
[Try it online](http://05ab1e.tryitonline.net/#code=w7jigqxK&input=WydjYXInLCAnZG9nJywgJ21hbicsICd5YXknXQ)
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 3 bytes
```
{z}
```
This is a code block (equivalent to a function; [allowed by default](https://codegolf.meta.stackexchange.com/q/2419/36398)) that expects the input on the stack and leaves the output on the stack.
[**Try it online!**](http://cjam.tryitonline.net/#code=cX4gICAgZSMgcmVhZCBpbnB1dCBhcyBhbiBhcnJheQp7en0gICBlIyBhY3R1YWwgY29kZSBibG9jawp-ICAgICBlIyBldmFsdWF0ZSBjb2RlIGJsb2NrCnAgICAgIGUjIGRpc3BsYXkgYXMgYXJyYXk&input=WyJjYXIiICJkb2ciICJtYW4iICJ5YXkiXQ)
[Answer]
# JavaScript ES6, ~~48~~ 46 bytes
```
a=>[...a[0]].map((n,x)=>a.map(a=>a[x]).join``)
```
I feel left out, we have no built in zip function. Thanks nicael for pointing out my type error.
Usage
```
(a=>[...a[0]].map((n,x)=>a.map(a=>a[x])))(["asd","dsa"]); //or whatever is above, might change due to edits
```
returns
```
["ad","ss","da"]
```
[Answer]
# Bash + BSD utilities, 27
```
sed s/./\&:/g|rs -c: -g0 -T
```
I/O via STDIN/STDOUT newline-separated strings.
You may need to install `rs` with `sudo apt install rs` or similar. Works out of the box on OS X.
The `-T` option to `rs` does the heavy lifting of the transposition. The rest is just formatting:
* The `sed` command simply inserts `:` after every character
* `-c:` specifies input columns are `:` separated
* `-g0` specifies output columns have zero width separation
If my reading of the `rs` manpage is correct, then the following **ought** to work for a score of 12, but unfortunately it doesn't work - see note below:
```
rs -E -g0 -T
```
### Example output:
```
$ printf "%s\n" car dog man yay |sed s/./\&:/g|rs -c: -g0 -T
cdmy
aoaa
rgny
$
```
If input is expected to be all printable ASCII, then the `:` may be replaced with some unprintable character, e.g. 0x7 `BEL`.
---
### Note
I wanted to understand why I couldn't get the `-E` option to work and get rid of the `sed` preprocessing. I found the [`rs` source code here](https://github.com/denghuancong/4.4BSD-Lite/blob/master/usr/src/usr.bin/rs/rs.c). As you can see, giving this option sets the `ONEPERCHAR` flag. However, there is nothing in the code that actually checks the state of this flag. So I think we can say that despite the fact that is option is documented, it is not implemented.
In fact, this option is documented in the Linux `rs` manpage:
>
> -E Consider each character of input as an array entry.
>
>
>
but not the OS X version.
[Answer]
# PHP, 82 bytes
```
function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;}
```
takes and returns an array of strings
**break down**
```
function f($a)
{
    foreach($a as$s)                    // loop through array $a
        foreach(str_split($s)as$i=>$c)  // split string to array, loop through characters
            $y[$i].=$c;                 // append character to $i-th result string
    return$y;
}
```
**examples**
```
$samples=[
    ["asd","dsa"], ["ad","ss","da"],
    ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"],
    ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"]
];
echo '
';
while ($samples)
{
    echo 'in: ';         print_r($x=array_shift($samples));
    echo 'out: ';        print_r(f($x));
    echo 'expected: ';   print_r(array_shift($samples));
    echo '
';
}
```
[Answer]
## APL, 3 bytes
```
↓⍉↑
```
`↑` takes the input strings and turns them into a char matrix.
`⍉` transposes the matrix.
`↓` splits back the rows of the resulting matrix into strings.
[Answer]
# K, 1 [byte](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
+
```
[Try it here!](http://johnearnest.github.io/ok/index.html?run=%2B(%22car%22%3B%22dog%22%3B%22man%22%3B%22yay%22))
Transpose
[Answer]
# Mathematica, 26 bytes
```
""<>#&/@(Characters@#)&
```
Anonymous function. Takes a string list as input and returns a string list as output. The Unicode character is U+F3C7, representing `\[Transpose]`. Works by converting to a character matrix, transposing, and converting back to a string list. If the input/output format was stretched, then a simple 5-byte transpose would work:
```
#&
```
[Answer]
# MATLAB / Octave, 4 bytes
```
@(x)x'
```
This defines an anonymous function. Input format is `['car'; 'dog'; 'man'; 'yay']`.
[**Try it here**](http://ideone.com/7g6VaE).
[Answer]
# Haskell, 41 bytes
```
f l=zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0
```
Or with a bit more air:
```
f l = zipWith ($) [map (!! n) | n <- [0..]] $
                  l <$ (l !! 0)
```
The second list is the list of words repeated “the length of a word” time. On each list of words, we select the n-th letter of each word, giving the result.
[Answer]
## Common Lisp, 62 bytes
```
(lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s))
```
The `map` function takes a result type (here `list`), a function *f* to apply and one or more sequences *s1*, ..., *sn*. All sequences are iterated in parallel. For each tuple of elements *(e1,...,en)* taken from those sequences, we call *(f e1 ... en)* and the result is accumulated in a sequence of the desired type.
We take a list of strings, say `("car" "dog" "man" "yay")`, and use `apply` to call `map`. We have to do this so that the input list is used as more arguments to `map`. More precisely, this:
```
(apply #'map 'list fn '("car" "dog" "man" "yay"))
```
... is equivalent to:
```
(map 'list f "car" "dog" "man" "yay")
```
And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls *f* as follows:
```
(f #\c #\d #\m #\y)
```
The anonymous lambda takes the list of arguments given to it and coerces it back to a string.
[Answer]
## Perl, 91 bytes
So lengthy one..
```
$l=<>;$p=index($l," ")+1;@i=split//,$l;for$a(0..$p-1){print$i[$a+$_*$p]for(0..$p);print" "}
```
[Try it here!](https://ideone.com/srDzwg)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
```
->a{a.map(&:chars).transpose.map &:join}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3NXTtEqsT9XITCzTUrJIzEouKNfVKihLzigvyi1NBwgpqVln5mXm1UPWKBQpu0dFKyYlFSjoKSin56SAqNzEPRFUmVirFxkIULlgAoQE)
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 24 bytes
Port of [my Ruby answer](https://codegolf.stackexchange.com/a/254848/11261).
```
:*&A|:transpose|:*&:join
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWO6y01BxrrEqKEvOKC_KLU2uAfKus_Mw8iPRNxQIFt-hopeTEIiUdBaWU_HQQlZuYB6IqEyuVYmMhChcsgNAA)
## Explanation
```
:* & A | :transpose | :* & :join
:* & A |                          # Map converting to character arrays, then
         :transpose |             # Transpose, then
                      :* & :join  # Map with join
```
[Answer]
# [Go](https://go.dev), 111 bytes
```
type S=[]string
func f(I S)S{O:=make(S,len(I[0]))
for _,s:=range I{for j,r:=range s{O[j]+=string(r)}}
return O}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBLasMwFKRbneLhlU3VULoqAR8gqxS8DKE8FNkoiSQjyQsjdJJuQqGH6FHa0_TJauhn4zFvRvPmzcvrYC_vI4oTDhI0KsOUHq0Lq6rXoXqbQn_3-GHDPEro2t3eB6fMwPrJCOjrDXRNF7frVuNJ1h0_S1Nvdvf7pmG9dfDM_bp1aMh5E_PgyN114ON2d9zftsWwdk1KzMkwOQPbVNZ-3jwse0dUDkg3iQBRcQvXGImVIDl23UBkAr30sG5JkR_F5XNVx0qgqzhUBztk0GgyzDhXif8SHfSc52gRM7rBkCDxf17aGrnoAp2-GFFAH_5Y6RAyYctac5oySOmXtYa0dHPpSeTQpZhyQ2RP5BHOphYrxUGsLKe-6Z-q_WFsZlRhLDGJfVd3uRT8Ag)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Simply transposes the input.
```
Õ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1Q&input=WyJtb25leSIsICJ0YWtlbiIsICJ0cnVzdCJd)
[Answer]
# Ruby, 46 bytes
Probably the first time that "Ruby strings aren't Enumerables" is actually biting me hard since I had to map the strings into arrays before processing. (Normally having to use `String#chars` isn't enough of a byte loss to matter, but since I need to map them, it stings a lot more)
```
->s{s.map!(&:chars).shift.zip(*s).map &:join}
```
[Answer]
# Clojure, 68 bytes
```
#(map(fn[g](reduce(fn[a b](str a(nth b g)))""%))(range(count(% 0))))
```
Maps a function which is just `reduce` (goes on elements of the list one by one and joins nth character of the string) on the range from 0 to length of the first string.
See it online: <https://ideone.com/pwhZ8e>
[Answer]
# C#, 53 bytes
```
t=>t[0].Select((_,i)=>t.Aggregate("",(a,b)=>a+b[i]));
```
C# lambda (`Func`) where the output is `IList<string>` and the output is `IEnumerable<string>`. I dont know how work `zip` in other language but I can't find a way to use the [C#'s one](https://msdn.microsoft.com/en-us/library/dd267698(v=vs.110).aspx) here. `Aggregate` fit the need well. No transpose in C#, there is [one](https://stackoverflow.com/a/12839486/1248177) in Excel but I wont use it.
[Try it online!](https://dotnetfiddle.net/sDajpJ)
]


[Question]
      [
The goal here is to simply reverse a string, with one twist:
Keep the capitalization in the same places.
Example Input 1: `Hello, Midnightas`
Example Output 1: `SathginDim ,olleh`
Example Input 2: `.Q`
Exmaple Output 2: `q.`
**Rules**:
* Output to STDOUT, input from STDIN
* The winner will be picked 13th of July on GMT+3 12:00 (One week)
* The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.
* Any punctuation ending up in a position where there was an upper-case letter must be ignored.

[Answer]
## Python, 71 bytes
```
lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))
```
[Try it online](http://ideone.com/fork/py1Kjj)
-3 bytes from Ruud, plus the inspiration for 2 more.
-4 more bytes from FryAmTheEggman
[Answer]
# Python 2, 73 bytes
Since the rules specify the input is ascii:
```
lambda s:''.join([z.lower,z.upper]['@'<c<'[']()for c,z in zip(s,s[::-1]))
```
All the credit goes to @Mego though, but I had not the reputation to just comment on his answer.
[Answer]
## Perl, 31 + 2 (`-lp`) = 33 bytes
*This solution is from [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) (13 bytes shorter thant mine).*
```
s%.%(lc$&gt$&?u:l)."c chop"%eeg
```
But you'll need `l` and `p` switches on. To run it :
```
perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg'
```
[Answer]
# Pyth, ~~13~~ ~~11~~ ~~10~~ 9 bytes
*Thanks to @FryAmTheEggman for reminding me about `V` and @LeakyNun for another byte.*
```
srV_Qm!/G
```
[Try it online!](http://pyth.tryitonline.net/#code=c3JWX1F9UnJHMQ&input=IkhlbGxvLCBNaWRuaWdodGFzIg)
now on mobile, updating link in a bit
[Answer]
## Python, 66 bytes
```
f=lambda s,i=0:s[i:]and(s[~i]*2).title()[~('@'<s[i]<'[')]+f(s,i+1)
```
Recurses through the indices `i`, taking the character `s[~i]` from the back and the case of `s[i]` from the front. Being capital is checked as lying in the contiguous range `@ABC...XYZ[`.
Credit to FryAmTheEggman from the `(_*2).title()` trick.
[Answer]
## TCC - 4 bytes
```
<>ci
```
[Try it online!](https://www.ccode.gq/projects/tcc.html?code=%3C%3Eci&input=Hello%2C%20Midnightas)
Explanation:
```
     - output is implicit in TCC
<>   - reverse string
  c  - preserve capitalization
   i - get input
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~75~~ ~~67~~ 65 bytes
Byte count assumes ISO 8859-1 encoding.
```
$
±·$`
O$^`\G[^·]
s{T`L`l`±.
T01`l`L`±.*·[A-Z]
±·
±(.)
$1±
·.
·
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAokCsKxwrckYApPJF5gXEdbXsK3XQoKc3tUYExgbGDCsS4KVDAxYGxgTGDCsS4qwrdbQS1aXQrCscK3CgrCsSguKQokMcKxCsK3LgrCtw&input=SGVsbG8sIE1pZG5pZ2h0YXMKLlEKLnE) (The first line enables a test suite with multiple linefeed-separated test cases.)
[Answer]
## JavaScript (ES6), ~~95~~ 83 bytes
```
s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join``
```
Edit: Saved a massive 12 bytes thanks to @edc65.
[Answer]
## Pyke, ~~11~~ ~~10~~ 9 bytes
```
_FQo@UhAl
```
[Try it here!](http://pyke.catbus.co.uk/?code=_FQo%40UhAl&input=Hello%2C+Midnightas)
```
_         -   reversed(input)
 F        -  for i in ^
   o      -      o+=1
  Q @     -     input[^]
     Uh   -    ^.is_upper()+1
       Al -   [len, str.lower, str.upper, ...][^](i)
          - "".join(^)
```
[Answer]
# [J](http://jsoftware.com), 30 bytes
```
(={"_1 toupper@]|.@,.])tolower
```
Doesn't support non-ASCII
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ ~~16~~ ~~15~~ 13 bytes
Thanks to **Emigna** for saving a 3 bytes!
Probably gonna get beat by Jelly... Code:
```
Âuvy¹Nè.lil}?
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4J1dnnCuU7DqC5saWx9Pw&input=SGVsbG8sIE1pZG5pZ2h0YXM).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes
```
@lr:?z:1ac.
h@u.,@A@um~t?|h.
```
### Explanation
* Main Predicate:
```
@lr                 Reverse the lowercase version of the Input
   :?z              Zip that reversed string with the Input
      :1a           Apply predicate 1 to each couple [char i of reverse, char i of Input]
         c.         Output is the concatenation of the result
```
* Predicate 1:
```
h@u.,               Output is the uppercase version of the first char of Input
     @A@um~t?       The second char of Input is an uppercase letter
             |      Or
              h.    Output is the first char of Input
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
PktGtk<)Xk5M(
```
[**Try it online!**](http://matl.tryitonline.net/#code=UGt0R3RrPClYazVNKA&input=J0hlbGxvLCBNaWRuaWdodGFzJw)
```
Pk      % Implicit inpput. Flip, lowercase
t       % Duplicate
Gtk<    % Logical index of uppercase letters in the input string
)       % Get letters at those positions in the flipped string
Xk      % Make them uppercase
5M(     % Assign them to the indicated positions. Implicit display
```
[Answer]
# TSQL, 175 bytes
Golfed:
```
DECLARE @ varchar(99)='Hello, Midnightas'
,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT
@i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT
SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o
```
Ungolfed
```
DECLARE @ varchar(99)='Hello, Midnightas'
,@o varchar(99)=''
,@i INT=0
WHILE @i<LEN(@)
  SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))
  FROM
    (SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/508510/reverse-a-string-while-maintaining-the-capitalization-in-the-same-places)**
[Answer]
## Actually, 25 bytes
```
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
```
[Try it online!](http://actually.tryitonline.net/#code=O2DDusOtdVkiw7nDuyJFwqNgTUDDuVJaYGlAxpJgTc6j&input=ImFiQ2Qi)
Explanation:
```
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
;                          create a copy of the input
 `úíuY"ùû"E£`M             for each character in input:
  úíuY                       0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0)
      "ùû"E£                 `û` if the character is lowercase else `ù` (str.lower vs str.upper)
              @ùRZ         make the other copy of the input lowercase, reverse it, and zip it with the map result
                  `i@ƒ`M   for each (string, function) pair:
                   i@ƒ       flatten, swap, apply (apply the function to the string)
                        Σ  concatenate the strings
```
[Answer]
# Haskell, ~~83~~ ~~80~~ ~~75~~ 71 bytes
The most straightforward way I could think of.
```
import Data.Char
f a|isUpper a=toUpper|1>0=toLower
zipWith f<*>reverse
```
[Answer]
# PowerShell, ~~154~~, ~~152~~, ~~99~~, 86 bytes
Thank you @TimmyD for saving me a whopping 47 bytes (I also saved an additional 6)
Thank you @TessellatingHeckler for saving an additional 13 bytes.
Latest:
```
param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})
```
Original:
```
param($a);$x=0;(($a[-1..-$a.length])|%{$_=$_.tostring().tolower();if([regex]::matches($a,"[A-Z]").index-contains$x){$_.toupper()}else{$_};$x++})-join''
```
Normal formatting:
Latest (looks best as two lines in my opinion):
```
param($a)
-join($a[$a.length..0] | %{("$_".ToLower(), "$_".ToUpper())[$a[$i++] -in 65..90]})
```
Explanation:
```
param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})
param($a)
# Sets the first passed parameter to variable $a
         -join(                                                                      )
# Converts a char array to a string
               $a[$a.length..0]
# Reverses $a as a char array
                               |%{                                                  }
# Shorthand pipe to foreach loop
                                  ("$_".ToLower(),"$_".ToUpper())
# Creates an array of the looped char in lower and upper cases
                                                                 [$a[$i++]-in65..90]
# Resolves to 1 if the current index of $a is upper, which would output "$_".ToUpper() which is index 1 of the previous array
```
Original:
```
param($a)
$x = 0
(($a[-1..-$a.length]) | %{
    $_ = $_.tostring().tolower()
    if([regex]::matches($a,"[A-Z]").index -contains $x){
            $_.toupper()
        }else{
            $_
        }
        $x++
    }
) -join ''
```
First time poster here, was motivated because I rarely see PowerShell, ~~but at ~~154~~ 152 bytes on this one... I can see why!~~ Any suggestions appreciated.
I have learned that I must completely change my way of thinking to golf in code and its fun!
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
⌽f¨⍨⊢≠f←819⌶
```
`819⌶` is the case folding function
`f←` because its name is long, we assign it to *f*
`⊢≠f` Boolean where text differs from lower-cased text
`f¨⍨` use that (1 means uppercase, 0 means lowercase) to fold each letter...
`⌽` ... of the reversed text
Handles non-ASCII according to the Unicode Consortium's rules.
[Answer]
## CJam, 22 bytes
```
q_W%.{el\'[,65>&{eu}&}
```
[Test it here.](http://cjam.aditsu.net/#code=q_W%25.%7Bel%5C'%5B%2C65%3E%26%7Beu%7D%26%7D&input=Hello%2C%20Midnightas)
[Answer]
# Racket, 146 bytes
```
(λ(s)(build-string(string-length s)(λ(n)((if(char-upper-case?(string-ref s n))char-upcase char-downcase)(list-ref(reverse(string->list s))n)))))
```
Racket is bad at this whole "golfing" thing.
*Shrug* As always, any help with shortening this would be much appreciated.
[Answer]
# Jolf, 21 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpxpZD8mzrMuX3BYaVM9cHhISHB4zrPOsw&input=SGVsbG8sIE1pZG5pZ2h0YXMKCi5R)
```
Μid?&γ._pXiS=pxHHpxγγ
```
## Explanation
```
Μid?&γ._pXiS=pxHHpxγγ
Μid                   (Μ)ap (i)nput with (d)is fucntion:
   ?        =pxHH     (H is current element) if H = lowercase(H)
    &γ._pXiS          and set γ to the uppercase entity in the reversed string
                 pxγ  lowercase γ
                    γ else, return γ
```
[Answer]
# [Perl 6](http://perl6.org), 29 bytes
```
$_=get;put .flip.samecase($_)
```
[Answer]
# C#, ~~86~~ 85 bytes
```
s=>string.Concat(s.Reverse().Select((c,i)=>s[i]>96?char.ToLower(c):char.ToUpper(c)));
```
A C# lambda where the input and the output is a string. You can try it on [.NetFiddle](https://dotnetfiddle.net/0NjPq2).
---
~~I am struggling to understand why I cant achieve to convert `char.ToLower(c)` to `c+32`. I hope to fix it!~~
12 bytes saved thanks to @PeterTaylor (`c|32` to add 32 to the ascii value of `c` and `c&~32` to substract 32). The result would be 72 bytes (but can fail on non alpha char).
```
s=>string.Join("",s.Reverse().Select((c,i)=>(char)(s[i]>96?c|32:c&~32)));
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~9~~ 2 bytes
```
Ṙ•
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwi4bmY4oCiIiwiIiwiSGVsbG8iXQ==)
[Answer]
# [Julia 1.0](http://julialang.org/), ~~73, 65~~  64 bytes
```
!s=prod(titlecase(s[end-i+1]^2)[2-('@'<s[i]<'[')] for i=keys(s))
```
[Try it online!](https://tio.run/##NcqxDsIgEADQ3a@44gDE1qSd26SDg4uDcSSYEIvl9ATTw6hfj5NvfrcXoWs/pVQ8PJc0qYyZ/MWxV2x8nBrctPbcadM1So6yZ4O2l0ZqC9e0AA53/2XFWpeRQ3pDJfaeKNVwwCniHLJjAWs4uRxmjDt8QJ2IfFj9@/Yoyg8 "Julia 1.0 – Try It Online")
-9 MarcMush
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 bytes
```
ŒlðUŒuT}¦n
```
[Try it online!](https://tio.run/##y0rNyan8///opJzDG0KPTioNqT20LO////8eQPF8HQXfzJS8zPSMksRiAA "Jelly – Try It Online")
Did I say this was extremely golfable by someone who understands `¦`? Turns out it's just understanding anything at all about chaining in general.
```
Œl            Lowercase the input,
   U          reverse it,
    Œu        then uppercase it
      T}¦     at indices where
  ð      n    the lowercase input doesn't equal the original input.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 139 bytes
```
#define B v[c+~i]
#define C(x,y)isupper(x)?toupper(y):tolower(y)
i,t,c;f(char*v){for(c=strlen(v);i<c/2;i++)t=C(B,v[i]),v[i]=C(v[i],B),B=t;}
```
[Try it online!](https://tio.run/##XY7NasMwEITveoqFXKRYbWmPVdyCc8kb9GB8cPXjLCiSkWUlIaSv7spOA6F7mJ35GJaVT52U07RS2qDTUEGqZfGDDbmTLT3xM8Nh7Hsd6Il9Rn@zZ/YevfXHxRLkkUthqNy3YZ3YxfhAZTnEYLWjiQncyJc3gUXBYrmlFU81NmzRHOfFK8arMorrtEIn7ag0bIaoLH4/7z/IIwvouv9MoZ8RugiHFh2dTRs6yWF@CNbZp7ph5EIgz43lS1BCVjX2dCm8NkyQpWFo5vfQj3F4zCZo/ZevME07ba2HLx@s@gU "C (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~114~~ ~~92~~ 78 bytes
```
~x=(b=reverse(lowercase(x));prod(i->b[i]-32('@'<x[i]<'['<b[i]-5<'v'),keys(b)))
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v67CViPJtii1LLWoOFUjJ788tSg5Eciq0NS0LijKT9HI1LVLis6M1TU20lB3ULepALJt1KPVbcCCpjbqZeqaOtmplcUaSZqamv8dijPyyxXqlDxSc3LydRR8M1PyMtMzShKLlbhgUnqBCHZilWMUgucIBA7RCdVK/wE "Julia 1.0 – Try It Online")
* -22 bytes thanks to amelies: use `prod`
* -10 bytes thanks to MarcMush: avoid `uppercase` and `isuppercase`
* -4 bytes thanks to MarcMush: use `keys(b)` instead of `1:length(b)`
[Answer]
# PHP, 128 bytes
```
$s=$argv[1];$l=strrev($s);for($i=0;$i<strlen($s);++$i){echo(strtolower($s[$i])!==$s[$i]?strtoupper($l[$i]):strtolower($l[$i]));}
```
I may attempt to optimize this further but I'll just leave it as is for now.
[Answer]
# Octave, ~~51~~ 50 bytes
~~`@(s)merge(isupper(s),b=flip(toupper(s)),tolower(b))`~~
```
@(s)merge(s>64&s<91,b=flip(toupper(s)),tolower(b))
```
]