text:
Leave a Comment
Task:
Make a program that leaves a comment on this question. The content should be 1234567890123456.
Edits:

You may leave your usernames and passwords as U and P if you are
using username and password. (if applicable)
No URL Shorteners (if applicable)
You may not use the browser console.

Welcome to PPCG! Interesting first post! Seems a bit hard in most languages though, but I think it's good anyway.

Please post a screenshot of your inbox at the end of this challenge...

You should maybe make a post on Meta where people can test their submissions, but this is completely optional.

@Loovjo You can always delete your comment

@Bálint That may be a bit tedious to do every time you test the program.

@Loovjo I can only post once every 40 minutes :( but I made the page.

Oh, by the way, if you decide to post on meta, you should maybe use another account, since you'll be getting a lot of unnecessary notifications otherwise.

I don't think creating a meta post to test answers is a good idea.

To the people testing their code: please delete your comment(s) after you submit them, to keep the comments on this challenge from getting unnecessarily long and spammy, and to make the mods' jobs easier.

Also, retrieving the access_token from a browser session is difficult (if not impossible) for some languages.

Does nobody else think this is underspecified? Like, how the hell do I do that? Aren't questions meant to be self-contained? Where's the link to the API docs?

@cat While I agree that the specifications are rather sparse, I think it's because there just isn't a whole that needs to be said. Also note that using the Stack Exchange API isn't required by the question, so including API docs in the question would be rather superfluous.

This works on specific languages only. Many languages do not support Internet.

Voting to close as unclear because looking at the existing answers and comments it seems to me that this needs a) to explicitly white-list the permitted inputs (on a plain reading answers may take no input, but some of them seem to be taking auth details and bypassing the implied requirement to use username and password to log in); b) to clarify what is meant by "You may leave your usernames and passwords as U and P, respectively" (which I would interpret as telling us to hardcode "U" and "P", but which others have clearly interpreted differently).

@PeterTaylor Thanks for the suggestions. I edited the question just now. Are there any other suggestions you would like me to add?

Can you clarify what you mean by URL shorteners? Clearly bit.ly and goo.gl would not be disallowed, but what about http://ppcg.lol, which is a custom domain owned by Quill that redirects to this site?

@Mego if you want to access this question, you have to use codegolf.stackexchange.com/questions/84546 and not ppcg.lol/q/84546 (I commented to Sirens to change his answer because he used ppcg)

1234567890123456 (this is not sent by script :P)

1234567890123456

1234567890123456

123456789023456

123456789023456

Javascript with jQuery, 127 bytes
$.post("//codegolf.stackexchange.com/posts/84546/comments",{comment:"1234567890123456",fkey:StackExchange.options.user.fkey})

Thanks to Ismael Miguel and nicael for a few bytes.
The fkey parameter is unique to your account, and can be found by examining local storage contents of your browser with a StackExchange page open. This code must be run in a browser with an open StackExchange session present. It automatically loads the fkey parameter from the browser's local storage (previous versions of this submission required it to be manually entered).
Unfortunately, the ppcg.lol URL can't be used, because it doesn't pass POST requests through.
Fun fact: if you attempt to run this code without the proper fkey value, you get an HTTP 418 response:

Example of how to find the fkey value in Chrome:

Apparently Winterbash stuff is still being stored. Neat.
For reference, the same thing in vanilla Javascript would be 314 bytes (thanks again to Ismael Miguel and nicael for some bytes off):
with(new XMLHttpRequest()){
open("POST","//codegolf.stackexchange.com/posts/84546/comments",1)
setRequestHeader("Content-type","application/x-www-form-urlencoded")
setRequestHeader("Content-length",62)
setRequestHeader("Connection","close")
send("comment=1234567890123456&fkey="+StackExchange.options.user.fkey}))}

I was just about to write this. Please add a Stack Snippet.

I like how you use the request to access the site instead of using selenium!

@NoOneIsHere A Stack Snippet isn't possible, because they run sandboxed, without access to the browser's cookie/session data. Additionally, I'm not certain if Stack Snippets even allow POST requests at all.

Instead of var http=new XMLHttpRequest();with(http){, you can do with(new XMLHttpRequest()){. Alternativelly, you can drop the http: from your URLs. Also, {"comment":"1234567890123456","fkey":localstorage.getItem('se:fkey')} can be just {comment:1234567890123456,fkey:localStorage.getItem`se:fkey`}. Notice that you wrote localstorage, when it MUST be localStorage. Final result: $.post("//codegolf.stackexchange.com/posts/84546/comments",{comment:1234567890123456,fkey:localStorage.getItem`se:fkey`}) (121 bytes)

I'm downvoting this answer. Not because my solution was completelly disregarded, but because it just simply doesn't work with localstorage. You MUST have localStorage!

@IsmaelMiguel Downvoting for accidentally missing the capitalization on one letter in code seems a bit ridiculous, but that's your call. It's fixed now.

@Mego No. Downvoting because it is broken is NOT ridiculous.

@IsmaelMiguel Downvoting because of a slight typo is.

@Mego Still broken. Javascript is case-sensitive.

@IsmaelMiguel Try it now - it was actually some of your golfing suggestions that broke it, along with me missing that the se:fkey parameter from localStorage needed to be sliced.

@Mego The "broken" part refered to localstorage not working. My suggestions weren't perfect, but, I wasn't expecting you to use them anyway. The only one I expected was changing localstorage to have the correct spelling. Incorrect spelling of it means that the answer won't work as is broken.

StackExchange.options.user.fkey is shorter than localStorage["se:fkey"].slice(0,32) :)

AppleScript with Safari, 269 287 bytes
tell application "Safari"
activate
tell window 1
set current tab to (make new tab with properties {URL:"http://codegolf.stackexchange.com/q/84546"})
delay 5
do JavaScript "$('a')[66].click();$('textarea')[0].val('1234567890123456');$('input')[5].click()" in current tab
end tell
end tell

To use this you need to enable Safari Developer Settings and then enable Allow JavaScript from Apple Events. I'm not sure if it's cheating or not to use the existing keychain + cookies but oh well.
I also managed to do this in OSX's Automator by just automating the clicks and keystrokes however I didn't think it stayed true to the idea of the challenge

Hello, and welcome to PPCG! This is great! That's not cheating. You also need to enable JS for all JavaScript answers.

Welcome to PPCG! While this is certainly a creative answer, it is not self-contained, as it does not take the username and password as input.

@PatrickRoberts Totally understand but the line between self contained and not gets a little blurry with this sort of prompt considering all the moving parts you need. Mego's answer involves pulling the token out of Chrome's traffic analyzer which is where I'd personally draw the grey area line. Mine's most certainly not entirely self contained that's for sure'

@PatrickRoberts Nowhere in the challenge does it say that taking the username and password as input is required. In fact, all it does say is (paraphrased) "post this comment to this question" and "you may leave username and password as U and P, respectively". This submission fulfills the requirements, and thus is valid.

@Sirens Thanks for the answer. I just edited the question so can you not use URL Shorteners?

It doesn't appear to work... I mean, it does click the flag link, not the commenting link.

The OP modified the challenge to disallow URL shorteners, which invalidates this answer until you swap ppcg.lol for codegolf.stackexchange.com.

I'm temporarily removing this post in compliance with our policy about answers not meeting the challenge specification for the reasons cited above. Please feel free to edit your answer and to flag it for moderator attention so it can be undeleted.

@nicael What OS version are you on? This still works for me on Sierra beta 6

Python 3.5 with Selenium Webdriver, 485 427 469 461 449 414 403 bytes:
from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()

A full program utilizing a simple Python selenium web driver solution. Works in Chrome, although it needs ChromeDriver installed to work. Works by renaming U and P to the user's Stack Exchange email and password, respectively. However, if there are any issues getting ChromeDriver installed, here is a FireFox solution that gets executed in the exact same manner as the above solution and does not need any drivers, although it is currently 1 byte longer at 414 404 bytes:
from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()

Also, if a function is wanted, here is a solution using an anonymous lambda function, currently standing at 513 455 497 489 477 449 431 bytes and using Chrome as the browser.
lambda U,P:exec("from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals())

However, if there are, again, any issues regarding ChromeDriver, here is the same type of solution but this time using Firefox, currently standing at 442 432 bytes:
lambda U,P:exec("from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals())

You call these lambda functions by simply renaming the function as anything valid and then calling with your email and password like a normal function. For instance, if the function were named H, you would call it like H(Email, Password).

Thank you so much for introducing me to Selenium Webdriver.

@Maltysen No problem. :)

Chrome is shorter than Firefox?

@EᴀsᴛᴇʀʟʏIʀᴋ Well, I could not get it working with Webdriver before. I finally have though, and my solution is now 11 bytes shorter! :D

Swift 2.2 on iOS, 380 bytes
let r = NSMutableURLRequest(URL:NSURL(string:"http://codegolf.stackexchange.com/posts/84546/comments")!)
r.HTTPMethod = "POST"
r.HTTPBody = try!NSJSONSerialization.dataWithJSONObject(["comment":"1234567890123456","fkey":UIWebView().stringByEvaluatingJavaScriptFromString("localstorage.getItem('se:fkey')")!],options:[])
NSURLSession.sharedSession().dataTaskWithRequest(r).resume()

Assumes the user is logged in to Code Golf with Safari and has cookies enabled.  Also assumes UIKit is implicitly imported and available.  JSON serialization is so verbose in Cocoa...  Might update this with a Swift 3 solution and optionally macOS/Linux testable answers.

stringByEvaluatingJavaScriptFromString brilliant

@cat it gets better.

I'm angry now. I didn't think it was possible to hate Obejctive-C more than I did...

Java 8 with Selenium Webdriver, 684 bytes:
import java.util.*;import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;class Leave_a_Comment_PPCG_Challenge_Golfed_Version_1{static void Y(String U,String P){WebDriver D=new FirefoxDriver();D.get("http://www.codegolf.stackexchange.com/users/login");D.findElement(By.name("email")).sendKeys(U);WebElement Z=D.findElement(By.name("password"));Z.sendKeys(P);Z.submit();D.get("http://www.codegolf.stackexchange.com/questions/84546");D.findElement(By.linkText("add a comment")).click();WebElement V=D.findElement(By.name("comment"));V.sendKeys("1234567890123456");D.findElement(By.xpath("//input[@value='Add Comment']")).click();}public static void main(String[]a){Scanner I=new Scanner(System.in);Y(I.next(),I.next());}}

A direct adaptation in Java 8 of my second full program answer in Python. Works perfectly in Firefox and asks for space separated email and password input immediately when the program starts. In other words, the input is in the format Email Password where the space in between the two is needed.

The code you have here is longer than 684, haha

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


text:
Dig to Australia - antipodes
Background
Countless generations of children have wondered where they would end up if they dug a hole directly downwards. It turns out that this would, unsurprisingly, be rather dangerous, but anyway...
Antipodes are points that are directly opposite each other on the Earth's surface. This means that if a line was drawn between the two points, it would pass through the centre of the Earth.
Challenge
Write a program or function that, given a point, finds its antipode.
In this challenge, points are represented using the longitude-latitude system and degrees, arc minutes and arc seconds. To find the antipode, swap the directions of each ordinate (N <-> S and W <-> E) and subtract the longitude ordinate from 180 degrees.
Example:
Take the point N 50 26 23 W 4 18 29. Swap the directions to give S 50 26 23 E 4 18 29. Subtract the longitude ordinate from 180 0 0 to give 175 41 31, leaving the antipode coordinates as S 50 26 23 E 175 41 31.
Rules
Input
A set of latitude-longitude coordinates, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.
Output
The latitude-longitude coordinates of the antipode, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.
Take reasonable to mean that each part of the coordinate can be distinguished unambiguously.
Specs

The direction for the latitude ordinate is N or S, and that for the longitude ordinate is W or E.
All coordinate values are integers. The degree value will be between 0 and 90 for latitude, and between 0 and 180 for longitude. The arc minute and arc second values for both ordinates will be between 0 and 59.
If all the values for an ordinate are 0, either direction is acceptable.
There is no need to zero-pad any values.
No latitude ordinate will ever  be larger than 90 degrees, and no longitude ordinate will ever be larger than 180 degrees.
Standard loopholes apply.

Test cases
N 50 26 23 W 4 18 29 -> S 50 26 23 E 175 41 31

S 43 9 9 E 0 0 5     -> N 43 9 9 W 179 59 55

N 0 0 0 E 0 0 0      -> S/N 0 0 0 W/E 180 0 0 (either direction fine in each case)

S 1 2 3 W 4 5 6      -> N 1 2 3 E 175 54 54

S 9 21 43 W 150 7 59 -> N 9 21 43 E 29 52 1

S 27 40 2 W 23 0 0   -> N 27 40 2 E 157 0 0

N 0 58 37 W 37 0 0   -> S 0 58 37 E 143 0 0

Useful links

Latitude and longitude
Antipodes
Arc minutes and arc seconds

This is code-golf, so the shortest answer in bytes wins!

Is this a reasonable format? Four inputs: array of 3 numbers, char, array of three numbers; separated by newlines

@LuisMendo Unless I am misunderstanding you, I can only see three inputs; I assume you would want an extra char? I would say that that is a reasonable format. By reasonable, I essentially mean that each part of the coordinate can be distinguished unambiguously.

Yes, I forgot the first char. Thanks!

@TheBikingViking is it considered reasonable to use 1 and -1 for N and S, and 2 and -2 as E and W? Also, what about using [0,170,3,8] for angles, the first 0 being redundant?

"Rather dangerous"? Mate, the real danger is once you get here.

http://www.findlatitudeandlongitude.com/antipode-map/

@busukxuan Apologies for not responding sooner. I would say that both of those formats are not reasonable, since the spec requires N, S, E, or W as a direction, while the redundant 0 introduces ambiguity as to which value represents which component of the ordinate.

@TheBikingViking Ok then.

05AB1E, 37 34 bytes
`60©3L<Rm*O3°648*s-®‰`s®‰s‚˜)'€ÃÂ‡

Explained
`                                      # split input to 4 lines with longitude on top
 60©3L<Rm*O                            # convert longitude to seconds
            3°648*                     # longitude 180 0 0 in seconds
                  s-                   # subtract our longitude from this
                    ®‰`                # get seconds part
                       s®‰             # get minute and degrees part
                          s‚˜)         # join to list
                              '€ÃÂ‡    # translate directions

Try it online
Edit: Saved 3 bytes thanks to Adnan.

You can compress "NEWS" to ‘€Ã‘ or even '€Ã if lowercase is allowed.

@Adnan: Nice! Didn't think of compressing since the string was so small already.

MATL, 51 bytes
'NS'tPXEii'WE'tPXE648e3i60:qXJZA-JYAtn3-?2:&)wJZAwh

Input format:
'N'
[50 26 23]
'W'
[4 18 29]

Output format:
S
50 26 23
E
175  41  31

Try it online!
Explanation
'NS'tPXE     % Take input (string) implicitly. Exchange 'N' and 'S'
i            % Take input (array)
i'WE'tPXE    % Take input (string). Exchange 'W' and 'E'
648e3        % Push 648000
i            % Take input (array)
60:qXJ       % Push [0 1 ... 59]. Copy into clipboard J
ZA           % Convert second input array from base 60 to decimal
-            % Subtract
JYA          % Convert to base 60
tn3-?        % If length exceeds 3
  2:&)       %   Split into first two elements and then the rest
  w          %   Swap
  JZA        %   Convert from base 60 to decimal
  wh         %   Swap, concatenate

There's a typo in your explanation on the second to last line: bnase.

@TheBikingViking Thank you! Corrected

JavaScript (ES6), 88 bytes
(a,b,c,d,e,f,g,h)=>[a<'S'?'S':'N',b,c,d,e<'W'?'W':'E',!(g|h)+179-f,g|h&&!h+59-g,h&&60-h]

Takes 8 parameters and returns an array as the result. Expects a to be one of N or S and similarly e to be one of W or E. Calculations:

f needs to be subtracted from 179 if either g or h is nonzero but 180 if both g and h are zero (because there is no borrow), thus !(g|h) is added to the 179.
g needs to be zero if both g and h are zero, thus g|h&&, otherwise it needs to be subtracted from 59 if h is nonzero but 60 if h is zero (because there is no borrow), thus !h is added to the 59.
h needs to be zero if it was already zero, otherwise it is simply subtracted from 60.

Another way to look at this is to notice that subtracting in binary is achieved by adding the 1s complement plus an additional 1. Translated to this problem, we take 179-f, 59-g and 59-h and add 1. 59-h + 1 is 60-h, but if this is 60 then it carries, so the desired result is zero if h was originally zero. We add 1 to 59-g if there's a carry from h, i.e. if h was originally zero. Again we have to allow for a carry, which this time happens if both g and h are zero, and we add 1 to 179-f in this case.

Racket, 199 bytes
(λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60)))))

That's horribly long.  There's probably some things I could do to shorten it further, but shudders I'm completely done.
Takes a cons pair of two lists: one for the latitude and one for the longitude.  Each list has the direction (as a lowercase Racket symbol) as its first item and following it the degrees, arc-minutes, and arc-seconds.  Outputs in the same format
Racket will interpret this pair of two lists as a single list with another list as its first element.  This is perfectly fine, since you can still access both latitude and longitude as if they were two lists in a pair.
Usage:
>    (
     (λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60)))))
     (cons (list 's 43 9 9) (list 'e 0 0 5)))
'((n 43 9 9) w 179 59 55)

Which can be interpreted by future code as '((n 43 9 9) (w 179 59 55)), two lists.

Pyth, 41 45 43 35 bytes
K60-"NS"ww-"EW"wA.D-*3^K3iEKK+.DGKH

Uses base-60 conversion to turn degrees and minutes into seconds.
I/O format:
N
[1,2,3]
E
[4,5,6]

It prints a line every time you input a line, so to have a good-looking format, you can either use the CLI and pipe the input, or more conveniently, use the online Pyth implementation.
In pseudocode:
K60                                              K = 60
   -"NS"w                                        "NS".remove(input())
         w                                       print(input())
          -"EW"w                                 "EW".remove(input())
                A.D                              G,H = divmod(
                   -*3^K3                          3*K**3 -
                         iEK                         baseToDec(input(),K)),
                            K                      K)
                             +.DGKH              divmod(G,K)+H

@LuisMendo same as yours, but comma separated lists, and no quotes

Python 2, 140 122 bytes
Updated:
def f(c):x=([180,0,0],[179,59,60])[1<sum(c[6:8])];print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(lambda x,y:x-y,x,c[5:8])

This uses a slightly different approach: setting the values to subtract from the longitude based on the minutes and seconds. If there are 0 mins and seconds, it subtracts 180 from the degrees, and if there are >0 mins and secs, it subtracts 179, 59, and 60 from the d, m, s respectively.
Original:
def f(c):v=divmod;m,s=v((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60);d,m=v(m,60);print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[d,m,s])

Takes input as a list: f(['N', 0, 0, 0, 'E', 0, 0, 0]), converts the longitude to decimal degrees, subtracts from 180, then converts back to degrees, minutes, seconds and re-constructs the list, flipping the directions in the process.
Un-golfed:
def f(c):
    minutes,seconds=divmod((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60)
    degrees,minutes=divmod(minutes,60)
    print ['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[degrees,minutes,seconds])

Try it

JavaScript, 138 137 129 124 112 110
2 bytes improvement inspired by @Neil´s code
f=a=>a.map((v,i,a)=>i%4?i>6?v&&60-v:i>5?(59-v+!a[7])%60:i>4?179-v+!(a[7]|a[6]):v:'NEWS'[3-'NEWS'.indexOf(v)]);

input = output = array containing 2x(1 uppercase char and 3 int)
tested in Firefox

ungolfed
f=a=>a.map((v,i,a)=>
i%4?
    i>6?v&&60-v              // 7: invert seconds - old: (60-v)%60
    :i>5?(59-v+!a[7])%60     // 6: invert minutes, increase if seconds are 0
    :i>4?179-v+!(a[7]|a[6])  // 5: invert degrees, increase if seconds and minutes are 0
    :v                       // 1,2,3: unchanged
:'NEWS'[3-'NEWS'.indexOf(v)] // 0,4: swap directions
);

tests

in	outexpected	ok?

ah I just see @Neil had the same idea, but some shorter parametrizing

C#, 310 269 bytes
float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();string A(string i){var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s[0][0]>82?"N":"S")+$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;}

The input is one string. You can try it on .NetFiddle.
Code
float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();
string A(string i) {
    var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;
    return (s[0][0]>82?"N":"S")
        +$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;
}

If I don't take a string as input but a char, float[], char, float[], I can do:
C#, 167 166 165 163 152 148 147 139 bytes
(s,n,e,w)=>{float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;};

Code
(s,n,e,w) => {
    float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;
    return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;
};

Also I can remove the 3600 and use ฐ instead to move to 164 characters and 166 bytes. Should I use it?

C#, 150 bytes
(s,n,m,p,e,w,x,y)=>{var t=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {t.TotalHours} {t:%m\\ s}";};

Code
(s,n,m,p,e,w,x,y) => {
    var z=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);
     return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {z.TotalHours} {z:%m\\ s}";
};

A more .NET way! I delegate all the logic to the .NET struct TimeSpan and I abuse the string formatting logic. Input is char, int, int, int, char, int, int, int. I share this one to give some ideas. Maybe someone will improve in a better way than me.

That is unfortunately verbose.

@Fawful I post another version with different arguments. Less verbose isn't? I still can't get rid of string.Join()...

Do note that this is C# 6.0

@TuukkaX since it is the lastest version of C#, I didn't specify it. I will if I use some un release feature like C#7 feature.

@onedaywhen AFAIK yes. C# lambda with more one line should use a scope {} and end with return.

Well, I don't see a return, I had to add it myself... Using your test a('N', new float[] { 50, 26, 23 }, 'W', new float[] { 4, 18, 29 }) I get S 50 26 23 E 175.6919 41.51642 30.98511 - would you consider this a pass?

@onedaywhen Oh indeed I forgot it! (I didnt in the count ^^).  And yes for the result. I didn't find a valid way to round, floor or ceil so I remove the cast. I think the error come from the way C# implement the floating point. (I might be wrong)

Python 3, 131 130 bytes
def f(w,x,y,z):S=60;d=divmod;a,b,c=y;l,m=d(648e3-c-S*b-S*S*a,S);return w,"N" if x=="S" else "S",d(l,S)+(m,),"E" if z=="W" else "W"

Formats: angles are tuples of the form (deg,min,sec), directions are of the form N. Outputs a quadruple of 2 angles, each followed by its direction.
Ungolfed version:
def f(latitude,NS,longitude,EW):
    degree,minute,second=longitude
    minute,second=divmod(648000-second-60*minute-60*60*degree,60)
    return latitude, "N" if NS=="S" else "S", divmod(minute,60)+(second,), "E" if EW=="W" else "W"

You can get this down to 120 bytes by doing def f(w,x,y,z):S=60;d=divmod;a,b,c=y;l,m=d(648e3-c-S*b-S*S*a,S);return w,["S","N"][x=="S"],d(l,S)+(m,),["W","E"][z=="W"] This works by using the fact that True and False can be interpreted as 1 and 0 , and hence a if b else c is equivalent to [c, a][b]. On a side note, I think that your original code has a typo; should  x=="W" be z=="W"?

C, 188
main(int c,char**v){int n=*v[1]==78?83:78,e=*v[5]==69?87:69,b=648000-(atoi(v[6])*3600+atoi(v[7])*60+atoi(v[8]));printf("%c %s %s %s %c %d %d %d\n",n,v[2],v[3],v[4],e,b/3600,b/60%60,b%60);}

Requires 8 program arguments, will fail otherwise. Pass arguments like N 50 26 23 W 4 18 29. Direction indicators N, S, E, W, must be capitalized.

PostGIS, 123 bytes
The Tool-For-The-Job is disappointingly verbose, partly because of SQL wordiness and partly due to the need to cast to geometry and back:
CREATE FUNCTION f(p geography)
RETURNS geography
AS 'SELECT ST_Affine(p::geometry,1,0,0,-1,180,0)::geography' LANGUAGE sql;

On the other hand, this single function will transform points, collections of points, or more complex shapes (such as the entire coastline of Australia and New Zealand).

Java, 199 177 or 151 or 134 Bytes
177 Bytes solution which prints result
void t(int...a){int i=648000-(a[5]*3600+a[6]*60+a[7]);System.out.println(a[0]=='N'?"S":"N"+" "+a[1]+" "+a[2]+" "+a[3]+" "+(a[4]=='E'?"W":"E")+" "+i/3600+" "+i/60%60+" "+i%60);}

151 Bytes solution which returns result as array
Object[]y(int...a){int i=648000-(a[5]*3600+a[6]*60+a[7]);return new Object[]{a[0]=='N'?"S":"N",a[1],a[2],a[3],a[4]=='E'?"W":"E",i/3600,i/60%60,i%60};}

134 Bytes if we used lambda notation
a->{int i=648000-a[5]*3600-a[6]*60-a[7];return new Object[]{a[0]=='N'?"S":"N",a[1],a[2],a[3],a[4]=='E'?"W":"E",i/3600,i/60%60,i%60};}

Befunge, 122 114 111 Bytes (110 characters)
~"N"-v
 v"N"_"S"
v>,&.&.&.~"W"-
_"E"v"W"
+:v >,&"´"\-&"Z"*&
v\_\.00..@.-\"<".-1\ <
>1-.:"Z"/"<"\-\"Z"%:#^_\..@

Input format:
N 50 26 23W 4 18 29

Notice the longitude direction and the arc seconds must be huddled together
You may test the code here

PHP, 148 bytes
same approach as my JavaScript answer, look there for a breakdown

+16 function overhead
+17 for $ signs
+12 for parantheses (different operator precedence)
+4 for foreach because PHP´s array_map has a huge overhead
+1 for (60-$v)%60 because $v&&60-$v casts to boolean in PHP
-8 by working on the original
-4 by using chr, ord and some arithmetics on the direction swap

function f(&$a){foreach($a as$i=>$v)$a[$i]=$i%4?($i>6?(60-$v)%60:($i>5?(59-$v+!$a[7])%60:($i>4?179-$v+!($a[7]|$a[6]):$v))):chr(($i?156:161)-ord($v));}

function works on original
format: array with 2x (1 uppercase char, 3 int)

tests
function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);}
$samples=[
N,50,26,23,W,4,18,29,   S,50,26,23,E,175,41,31,
S,43,9,9,E,0,0,5,       N,43,9,9,W,179,59,55,
N,0,0,0,E,0,0,0,        S,0,0,0,W,180,0,0,
S,1,2,3,W,4,5,6,        N,1,2,3,E,175,54,54,
S,9,21,43,W,150,7,59,   N,9,21,43,E,29,52,1,
S,27,40,2,W,23,0,0,     N,27,40,2,E,157,0,0,
N,0,58,37,W,37,0,0,     S,0,58,37,E,143,0,0,
];
while ($samples)
{
    $xx=$x=array_splice($samples,0,8);
    $ee=$e=array_splice($samples,0,8);
    func($x); test($xx,$ee,$x);
    func($e); test($ee,$xx,$e);
}

abandoned ideas

no loop approach with carry flags: +5
loop backwards with carry flags: +7
I could turn this into a program for PHP<5.4, but never mind: -3

source: Stack Exchange

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

sort: votes


text:
Compute the maximum number of runs possible for as large a string as possible
[This question is a follow up to Compute the runs of a string ]

A period p of a string w is any positive integer p such that w[i]=w[i+p]
  whenever both sides of this equation are defined. Let per(w) denote
  the size of the smallest period of w . We say that a string w is
  periodic iff per(w) <= |w|/2.

So informally a periodic string is just a string that is made up from another string repeated at least once.  The only complication is that at the end of the string we don't require a full copy of the repeated string as long as it is repeated in its entirety at least once.
For, example consider the string x = abcab. per(abcab) = 3 as x[1] = x[1+3] = a, x[2]=x[2+3] = b and there is no smaller period. The string abcab is therefore not periodic.  However, the string ababa is periodic as per(ababa) = 2.
As more examples, abcabca, ababababa and abcabcabc are also periodic.
For those who like regexes, this one detects if a string is periodic or not:
\b(\w*)(\w+\1)\2+\b

The task is to find all maximal periodic substrings in a longer string.  These are sometimes called runs in the literature.

A substring w is a maximal periodic substring (run) if it is periodic and neither w[i-1] = w[i-1+p] nor w[j+1] = w[j+1-p].  Informally, the "run" cannot be contained in a larger "run"
  with the same period.

Because two runs can represent the same string of characters occurring in different places in the overall string, we will represent runs by intervals. Here is the above definition repeated in terms of intervals.

A run (or maximal periodic substring) in a string T is an interval
  [i...j] with j>=i, such that

T[i...j] is a periodic word with the period p = per(T[i...j])
It is maximal. Formally, neither T[i-1] = T[i-1+p] nor T[j+1] = T[j+1-p].  Informally, the run cannot be contained in a larger run
  with the same period.

Denote by RUNS(T) the set of runs in string T.
Examples of runs

The four maximal periodic substrings (runs) in string T = atattatt are T[4,5] = tt, T[7,8] = tt, T[1,4] = atat, T[2,8] = tattatt.
The string T = aabaabaaaacaacac contains the following 7 maximal periodic substrings (runs):
T[1,2] = aa, T[4,5] = aa, T[7,10] = aaaa, T[12,13] = aa, T[13,16] = acac, T[1,8] = aabaabaa, T[9,15] = aacaaca.
The string T = atatbatatb contains the following three runs. They are:
T[1, 4] = atat, T[6, 9] = atat and  T[1, 10] = atatbatatb.

Here I am using 1-indexing.
The task
Write code so that for each integer n starting at 2, you output the largest numbers of runs contained in any binary string of length n.
Score
Your score is the highest n you reach in 120 seconds such that for all k <= n, no one else has posted a higher correct answer than you.  Clearly if you have all optimum answers then you will get the score for the highest n you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it.
Languages and libraries
You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.
Example optima
In the following: n, optimum number of runs, example string.
2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011

What exactly should my code output?
For each n your code should output a single string and the number of runs it contains.
My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.
Leading answers

49 by Anders Kaseorg in C. Single threaded and run with L = 12 (2GB of RAM).
27 by cdlane in C.

You know what do with the results from this challenge...

@MartinEnder Yes!  I am hoping someone will come up with something better than the current super naive effort. Or at least code it in nim :)

If you only want us to consider only {0,1} -strings, please explicitly state that. Otherwise the alphabet could possibly be infinite, and I don't see why your testcases should be optimal, because it seems you only searched {0,1} strings too.

@flawr I have edited the question along the lines you suggested. The alphabet can't be any larger than the length of the string of course.

@flawr, I searched strings over a ternary alphabet for n up to 12 and it never beat the binary alphabet. Heuristically I would expect that a binary string should be optimal, because adding more characters increases the minimum length of a run.

In the optimum results above you have "12 7 001001010010" but my code pumps out "12 8 110110011011" where period 1 runs are (11, 11, 00, 11, 11), period 3 runs are (110110, 011011) and there's a period 4 run (01100110) -- where am I going wrong in my run counting?

@cdlane I think you are right there is a bug in orlp's runs function. Can you provide answers for n =2..22 instead so I can put them in the question or a working runs function I can use by any chance please?

The example optima for n = 5, n = 13 are wrong; see comments on cdlane’s answer. I am confident in the optima posted on my answer; I’ve verified them against a dumb Python implementation for n ≤ 21.

@cdlane 0000 has one run. Consider the period of 000...  it is always 1 no matter how many zeros.

I now readily accept that there is only one period 1 run in '0000', but how does that negate the period 2 run that it also contains?

Refer back to the definition .  Let per(w) denote the size of the smallest period of w .  There is no substring with smallest period length 2.

C
This does a recursive search for optimal solutions, heavily pruned using an upper bound on the number of runs that could be finished by the unknown remainder of the string.  The upper bound computation uses a gigantic lookup table whose size is controlled by the constant L (L=11: 0.5 GiB, L=12: 2 GiB, L=13: 8 GiB).
On my laptop, this goes up through n = 50 in 100 seconds; the next line comes at 142 seconds.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#define N (8*sizeof(unsigned long long))
#define L 13
static bool a[N], best_a[N];
static int start[N/2 + 1], best_runs;
static uint8_t end_runs[2 << 2*L][2], small[N + 1][2 << 2*L];

static inline unsigned next_state(unsigned state, int b)
{
    state *= 2;
    state += b;
    if (state >= 2 << 2*L) {
        state &= ~(2 << 2*L);
        state |= 1 << 2*L;
    }
    return state;
}

static void search(int n, int i, int runs, unsigned state)
{
    if (i == n) {
        int r = runs;
        unsigned long long m = 0;
        for (int p = n / 2; p > 0; p--) {
            if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
                m |= 1ULL << start[p];
                r++;
            }
        }
        if (r > best_runs) {
            best_runs = r;
            memcpy(best_a, a, n*sizeof(a[0]));
        }
    } else {
        a[i] = false;
        do {
            int r = runs, bound = 0, saved = 0, save_p[N/2], save_start[N/2], p, s = next_state(state, a[i]);
            unsigned long long m = 0;
            for (p = n/2; p > i; p--)
                if (p > L)
                    bound += (n - p + 1)/(p + 1);
            for (; p > 0; p--) {
                if (a[i] != a[i - p]) {
                    if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
                        m |= 1ULL << start[p];
                        r++;
                    }
                    save_p[saved] = p;
                    save_start[saved] = start[p];
                    saved++;
                    start[p] = i + 1 - p;
                    if (p > L)
                        bound += (n - i)/(p + 1);
                } else {
                    if (p > L)
                        bound += (n - (start[p] + p - 1 > i - p ? start[p] + p - 1 : i - p))/(p + 1);
                }
            }
            bound += small[n - i - 1][s];

            if (r + bound > best_runs)
                search(n, i + 1, r, s);
            while (saved--)
                start[save_p[saved]] = save_start[saved];
        } while ((a[i] = !a[i]));
    }
}

int main()
{
    for (int n = 0; n <= N; n++) {
        if (n <= 2*L) {
            for (unsigned state = 1U << n; state < 2U << n; state++) {
                for (int b = 0; b < 2; b++) {
                    int r = 0;
                    unsigned long long m = 0;
                    for (int p = n / 2; p > 0; p--) {
                        if ((b ^ state >> (p - 1)) & 1) {
                            unsigned k = state ^ state >> p;
                            k &= -k;
                            k <<= p;
                            if (!(k & ~(~0U << n)))
                                k = 1U << n;
                            if (!((m | ~(~0U << 2*p)) & k)) {
                                m |= k;
                                r++;
                            }
                        }
                    }
                    end_runs[state][b] = r;
                }
                small[0][state] = end_runs[state][0] + end_runs[state][1];
            }
        }

        for (int l = 2*L < n - 1 ? 2*L : n - 1; l >= 0; l--) {
            for (unsigned state = 1U << l; state < 2U << l; state++) {
                int r0 = small[n - l - 1][next_state(state, 0)] + end_runs[state][0],
                    r1 = small[n - l - 1][next_state(state, 1)] + end_runs[state][1];
                small[n - l][state] = r0 > r1 ? r0 : r1;
            }
        }

        if (n >= 2) {
            search(n, 1, 0, 2U);
            printf("%d %d ", n, best_runs);
            for (int i = 0; i < n; i++)
                printf("%d", best_a[i]);
            printf("\n");
            fflush(stdout);
            best_runs--;
        }
    }
    return 0;
}

Output:
$ gcc -mcmodel=medium -O2 runs.c -o runs
$ ./runs
2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011
23 17 00100101001011010010100
24 18 001001100100110110011011
25 19 0010011001000100110010011
26 20 00101001011010010100101101
27 21 001001010010110100101001011
28 22 0010100101101001010010110100
29 23 00101001011010010100101101011
30 24 001011010010110101101001011010
31 25 0010100101101001010010110100101
32 26 00101001011010010100101101001011
33 27 001010010110100101001011010010100
34 27 0001010010110100101001011010010100
35 28 00100101001011010010100101101001011
36 29 001001010010110100101001011010010100
37 30 0010011001001100100010011001001100100
38 30 00010011001001100100010011001001100100
39 31 001001010010110100101001011010010100100
40 32 0010010100101101001010010110100101001011
41 33 00100110010001001100100110010001001100100
42 35 001010010110100101001011010110100101101011
43 35 0001010010110100101001011010110100101101011
44 36 00101001011001010010110100101001011010010100
45 37 001001010010110100101001011010110100101101011
46 38 0010100101101001010010110100101001011010010100
47 39 00101101001010010110100101101001010010110100101
48 40 001010010110100101001011010010110101101001011010
49 41 0010100101101001010010110100101101001010010110100
50 42 00101001011010010100101101001011010110100101101011
51 43 001010010110100101001011010110100101001011010010100

Here are all optimal sequences for n ≤ 64 (not just the lexicographically first), generated by a modified version of this program and many hours of computation.
A remarkable nearly-optimal sequence
The prefixes of the infinite fractal sequence
1010010110100101001011010010110100101001011010010100101…

that is invariant under the transformation 101 ↦ 10100, 00 ↦ 101:
  101   00  101   101   00  101   00  101   101   00  101   101   00  …
= 10100 101 10100 10100 101 10100 101 10100 10100 101 10100 10100 101 …

seem to have very nearly optimal numbers of runs—always within 2 of optimal for n ≤ 64. The number of runs in the first n characters divided by n approaches (13 − 5√5)/2 ≈ 0.90983. But it turns out this is not the optimal ratio—see comments.

Thank you the answer and your corrections.  What do you think the prospects are for a non brute force solution ?

@Lembik I don’t know. I think my current solution is somewhat faster than o(2^N) given enough memory, but it’s still exponential. I haven’t found a direct formula that completely skips the search process, but one could exist. I conjecture that the Thue–Morse sequence is asymptotically optimal with N⋅5/6 − O(log N) runs, but it seems to stay a handful of runs behind the actual optimum.

Interestingly, 42/50 > 5/6.

@Lembik One should always expect asymptotic predictions to sometimes be beaten by small amounts. But actually I was completely wrong—I found a much better sequence that seems to be approaching N⋅(13 − 5√5)/2 ≈ N⋅0.90983 runs.

Very impressive. I think the 0.90983 conjecture is not right however. Check out https://bpaste.net/show/287821dc7214 . It has length 1558 and has 1445 runs.

@Lembik That’s a fascinating sequence. Most of it consists of a repeated block of length 492 (echo edfcff|sed 's/f/ded/g;s/e/cdb/g;s/d/abc/g;s/c/babb0b/g;s/b/a11/g;s/a/010/g'), and just repeating that block arbitrarily often gives a runs-to-length ratio approaching 77/82 ≈ 0.93902.

Check my algorithm at stackoverflow with that it takes <1s to compute the first 64 solutions. Here is the output for 100 after 31.2 seconds: 100 88 31.2 0010100101101001010010110100101000100101001011010010100101101001010001010010110100101001011010010100

Since it's not a race if there's only one horse, I'm submitting my solution though it's only a fraction the speed of Anders Kaseorg's and a only a third as cryptic.  Compile with:

gcc -O2 run-count.c -o run-count

The heart of my algorithm is a simple shift and XOR scheme:

A run of zeros in the XOR result that's greater than or equal to the current period/shift indicates a run in the original string for this period.  From this you can tell how long the run was and where it starts and ends.  The rest of the code is overhead, setting up the situation and decoding the results.
I'm hoping it will make at least 28 after two minutes on Lembik's machine.  (I wrote a pthread version, but only managed to make it run even slower.)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

enum { START = 0, WIDTH } ;

// Compare and shuffle just one thing while storing two
typedef union {
    uint16_t token;
    uint8_t data[sizeof(uint16_t)];
} overlay_t;

#define SENTINAL (0)  // marks the end of an array of overlay_t

#define NUMBER_OF_BITS (8 * sizeof(uint64_t))

void period_runs(uint64_t xor_bits, uint8_t nbits, uint8_t period, overlay_t *results) {

    overlay_t *results_ptr = results;
    uint8_t count = 0;

    for (uint8_t position = 0; position < nbits; position++) {

        if (xor_bits & 1ULL) {

            if ((nbits - position) < period) {
                break;  // no room left to succeed further
            }

            if (count >= period) {  // we found a run

                results_ptr->data[START] = position - (count - 1);
                results_ptr->data[WIDTH] = period + count;
                results_ptr++;
            }

            count = 0;
        } else {

            count++;
        }

        xor_bits >>= 1;
    }

    if (count >= period) {  // process the final run, if any

        results_ptr->data[START] = 0;
        results_ptr->data[WIDTH] = period + count;
        results_ptr++;
    }

    results_ptr->token = SENTINAL;
}

void number_runs(uint64_t number, uint8_t bit_length, overlay_t *results) {

    overlay_t sub_results[bit_length];
    uint8_t limit = bit_length / 2 + 1;
    uint64_t mask = (1ULL << (bit_length - 1)) - 1;

    overlay_t *results_ptr = results;
    results_ptr->token = SENTINAL;

    for (uint8_t period = 1; period < limit; period++) {

        uint64_t xor_bits = mask & (number ^ (number >> period));  // heart of the code
        period_runs(xor_bits, bit_length - period, period, sub_results);

        for (size_t i = 0; sub_results[i].token != SENTINAL; i++) {

            bool stop = false;  // combine previous and current results

            for (size_t j = 0; !stop && results[j].token != SENTINAL; j++) {

                // lower period result disqualifies higher period result over the same span
                stop = (sub_results[i].token == results[j].token);
            }

            if (!stop) {

                (results_ptr++)->token = sub_results[i].token;
                results_ptr->token = SENTINAL;
            }
        }

        mask >>= 1;
    }
}

int main() {

    overlay_t results[NUMBER_OF_BITS];

    for (uint8_t bit_length = 2; bit_length < 25; bit_length++) {

        int best_results = -1;
        uint64_t best_number = 0;

        for (uint64_t number = 1ULL << (bit_length - 1); number < (1ULL << bit_length); number++) {

            // from the discussion comments, I should be able to solve this
            // with just bit strings that begin "11...", so toss the rest
            if ((number & (1ULL << (bit_length - 2))) == 0ULL) {

                continue;
            }

            uint64_t reversed = 0;

            for (uint8_t i = 0; i < bit_length; i++) {

                if (number & (1ULL << i)) {

                    reversed |= (1ULL << ((bit_length - 1) - i));
                }
            }

            if (reversed > number) {

                continue;  // ~ 1/4 of bit_strings are simply reversals, toss 'em
            }

            number_runs(number, bit_length, results);
            overlay_t *results_ptr = results;
            int count = 0;

            while ((results_ptr++)->token != SENTINAL) {

                count++;
            }

            if (count > best_results) {

                best_results = count;
                best_number = number;
            }
        }

        char *best_string = malloc(bit_length + 1);
        uint64_t number = best_number;
        char *string_ptr = best_string;

        for (int i = bit_length - 1; i >= 0; i--) {

            *(string_ptr++) = (number & (1ULL << i)) ? '1' : '0';
        }

        *string_ptr = '\0';

        printf("%u %d %s\n", bit_length, best_results, best_string);

        free(best_string);
    }

    return 0;
}

Output:
> gcc -O2 run-count.c -o run-count
> ./run-count
2 1 11
3 1 110
4 2 1100
5 2 11000
6 3 110011
7 4 1100100
8 5 11001100
9 5 110010011
10 6 1100110011
11 7 11001100100
12 8 110110011011
13 8 1100100010011
14 10 11001001100100
15 10 110010011001000
16 11 1100100110010011
17 12 11001100100110011
18 13 110011001001100100
19 14 1101001011010010100
20 15 11010110100101101011
21 15 110010011001001100100
22 16 1100101001011010010100
23 17 11010010110100101001011
24 18 110100101001011010010100
25 19 1100100110010001001100100
26 20 11010010100101101001010010
27 21 110010011001000100110010011
28 22 1101001010010110100101001011

Welcome second horse! Small query, why do you and the other answer suggest -O2 instead of -O3?

@Lembik, with -O2 optimization, I could measure a time difference running the code but I couldn't measure any additional with -O3. Since we're supposedlly trading off safetly for speed, I figured the highest level that actually made a difference was best. If you believe my code will rank higher with -O3, go for it!

-O3 isn't intended to be "unsafe".  It enables auto-vectorization, but there's probably nothing to vectorize here.  It can sometimes make code slower, e.g. if it uses a branchless cmov for something where a branch would have predicted very well.  But usually it should help.  It's usually worth trying clang as well, to see which of gcc or clang make better code for a specific loop.  Also, it almost always helps to use -march=native, or at least -mtune=native if you still want a binary that runs anywhere.

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


text:
Reverse a string while maintaining the capitalization in the same places
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.

Is that with or without the outprinting? Is that with or without the string?

"Any punctuation ending up in a position where there was an upper-case letter must be ignored.", isn't the second example inconsistent with this rule?

It is consistent with the rule because punctuations do not have an uppercase variation.

TCC - 4 bytes
<>ci

Try it online!
Explanation:
     - output is implicit in TCC
<>   - reverse string
  c  - preserve capitalization
   i - get input

The link to the online interpreter is dead. I don't even know where this language is anymore

Python, 71 bytes
lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))

Try it online
-3 bytes from Ruud, plus the inspiration for 2 more.
-4 more bytes from FryAmTheEggman

lambda s:''.join([z.lower(),z.upper()][c.isupper()]for c,z in zip(s,s[::-1])) is three bytes shorter

@Ruud Thanks! Moving the function call to outside of the list selection saves 2 more!

(z*2).title()[c.isupper()-1] should work.

You could win another byte with ~c.isupper() instead of c.isupper()-1

This doesn't get input from stdin or output to stdout...

@ArtOfWarfare Functions are allowed by default.

Perl, 31 + 2 (-lp) = 33 bytes
This solution is from @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'

Hello, and welcome to PPCG! This is great!

Very nice indeed! I've never used-a autosplit, I feel I could have used this many times in the past! I need to remember that! I think you can save another byte using map...,... instead of map{...}... as you have $F at the start though! :)

Shorter code (31+2 bytes): perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg

Notice that -a is implied by -F

@TonHospel wow, thank you very much and well done, that's some quite nice code! About -a (and -n) being implied by -F, I read it a while ago on perlrun, tried it, but it didn't work; but I tried it again now and it works fine so I'm guessing I did something wrong back then. Thanks.

The -n and -a options were not always implied by -F. You probably tested on an older perl version

@TonHospel oh right, probably, since I changed my perl version since, that's probably it. Thanks again

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.

Can you use the ascii value of '@' and '[' to gain 2 bytes?

Unfortunately no, I'd have to use ord(c), integer and string comparison do not cope very well in Python

Pretty much what I got, but you were first +1

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!
now on mobile, updating link in a bit

srV_Qm!rId0 is 11, but I think it might be possible to shorten that map...

@FryAmTheEggman Remove the d and you saved a byte.

srV_Qm!/G should save a byte

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.

Pyke, 11 10 9 bytes
_FQo@UhAl

Try it here!
_         -   reversed(input)
 F        -  for i in ^
   o      -      o+=1
  Q @     -     input[^]
     Uh   -    ^.is_upper()+1
       Al -   [len, str.lower, str.upper, ...][^](i)
          - "".join(^)

It first gave me an error, then at the same time the correct answer. http://i.imgur.com/uTcH27F.png

That always happens, you can click disable warnings to turn that off.

Aha, okay. Sorry, I'm not good with Pyke

Might be because I'm the only guy using it

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.

s=>r=[...l=s.toLowerCase()].reverse().map((c,i)=>s[i]!=l[i]?c.toUpperCase():c).join`` -10

@edc65 Thanks! (Note: the r= is unnecessary.)

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! (The first line enables a test suite with multiple linefeed-separated test cases.)

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

S.l_v¹lRNèyiu}? is 1 byte shorter

@Emigna Wow thanks! That is very clever.

Âuvy¹Nè.lilë}? is 14. Just happy I can help you for once :)

@Emigna That is amazing! Very nice use of bifurcate :).

Ruvy¹Nè.lil}? actually. I didn't use the bifurcation and forgot to remove the else. So 13.

@Emigna At least we're tied with Pyth. Now we just need to defeat APL :p.

J, 30 bytes
(={"_1 toupper@]|.@,.])tolower

Doesn't support non-ASCII

"toupper" "tolower" can't you use code points to shorten it?

@LeakyNun Maybe but I can't really say for sure

@LeakyNun It's surprising, but I think it's very unlikely this should could be shortened in J.

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

MATL, 13 bytes
PktGtk<)Xk5M(

Try it online!
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

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!

Hello, and welcome to PPCG! This is great!

Welcome to PPCG! Nice to see another PowerShell user around here. You can cut out quite a bit by replacing the .tostring() with quotes, and by using ASCII integer manipulation rather than regex. Try the following, for 105 bytes -- param($a)-join($a[$a.length..0]|%{if(($x=$a[$i++])-le90-and$x-ge65){"$_".ToUpper()}else{"$_".ToLower()}}).

Brilliant! We can make that even shorter by using a range instead of -le and -ge: param($a)-join($a[$a.length..0]|%{if(65..90-contains$a[$i++]){"$_".ToUpper()}else{"$_".ToLower()}})

X-inY is shorter than Y-containsX, and you can change your if for the fake ternary operator to get 86 bytes - param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})

Man, I feel like I've missed out on a lot of tricks having never code golfed before. Its almost like learning to code all over again!

Actually, 25 bytes
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ

Try it online!
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

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

If you swap the parameters of (#), k can be rewritten in point-free style: k=reverse>>=zipWith(#), that saves a couple bytes :)

The second line can be point-free in b as f a|isUpper a=toUpper|1>0=toLower, though this conflicts with Flonk's improvement.

You can use xnor's version of f and rewrite Flonk's k to zipWith f<*>reverse.

Don’t you need to eliminate the parameter s?

Yes, and you're also allowed to cut the k=.

Sure, I copied the wrong verision,thanks

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

hardcoding the input ?

@cat that is the only way. In sql, there is no STDIN or input command. If you look at stackoverflow that is how all the questions are solved - you can also look at my other answers on codegolf

Oh, yeah, I definitely remember having this conversation wih a SQL user before (you, maybe). That's weird, but should be fine.

@cat we have not had this conversation before, but you did help me with a byte count earlier

Jolf, 21 bytes
Try it here!
Μ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 γ

(d)is function... Sacrifice spelling for the sake of golf!

Perl 6, 29 bytes
$_=get;put .flip.samecase($_)

Dyalog APL, 12 bytes
⌽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.

CJam, 22 bytes
q_W%.{el\'[,65>&{eu}&}

Test it here.

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.

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

It would be c|32 instead of c+32, but it won't work with non-alpha characters.

@PeterTaylor It works great! Thank you!

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.

Tips for golfing in Racket / Scheme

Jelly, 13 10 bytes
ŒlðUŒuT}¦n

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.

Vyxal r, 9 2 bytes
Ṙ•

Try it online!

Julia 1.0, 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!

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

Various tweaks to get to 93 bytes
https://tio.run/##yyrNyUw0rPj/v67CViPJNie/PLUoObE4VU@jKLUstag4VaNCU9O6oCg/RSNT1y6zuLSgAKJAoyI6M1ZTwV4BIZIEFrFSANE6hlY5qXnpJRkaSZqamv8dijPyyxXqlDxSc3LydRR8M1PyMtMzShKLlbhgUnqBSv8B

78 bytes by avoiding (is)uppercase Try it online!

Julia 1.0, 73, 65  64 bytes
!s=prod(titlecase(s[end-i+1]^2)[2-('@'<s[i]<'[')] for i=keys(s))

Try it online!
-9 MarcMush

64 bytes

C (gcc), 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!

134 bytes

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

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.

As notices are allowed, there are a few parts you can optimize at. Instead of a for loop, you can do a while loop and set the char to test directly: while($a=ord($s[$i++])). With that, as we use ord() you can test based on the char number: $a<90&&$a>65. However, for the strtoupper and lower you need to correct the index number as in the loop it was already increased, this means: strtolower($l[$i-1]). This should save quite some bytes

Javascript (using external library) (224 bytes)
(s)=>{t=_.From(s);var cnt=t.Count();var caps=t.Select(x=>{return x.toUpperCase()===x&&x.toLowerCase()!==x}).ToArray(),i=-1;return t.AggregateRight((a,b)=>{i++;var c=caps[i];return c?a+b.toUpperCase():a+b.toLowerCase()},"");}

Disclaimer: Using a library I wrote to bring C#'s LINQ to Javascript

Calling out the person who downvoted this without an explanation. Any reason for that?

It's likely that they wanted you to count the library as well, although using an external library is fully within the boundaries of standard policy.

I'm not downvoter, but If you are using an external library, at least mention the name in your answer, and for an obscure library, please provide a link to the repository.

VIM, 46 bytes
It'd be three bytes g~G if we didn't need to read from stdin or write to stdout, but oh well...
vim -es '+normal! g~G' '+%print|q!' /dev/stdin

To test this, run
echo "testString" | vim -es '+normal! g~G' '+%print|q!' /dev/stdin

This is my first submission on here, not sure if this kind of submission is acceptable.

Nice, I love golfing in vim! However, this program doesn't actually reverse the string, it just toggles the capitalization. You can reverse the string with :se ri<cr>C<C-r>" but then you'll have to figure how to capitalize the right letters.

@DrGreenEggsandIronMan Oh man I completely missed that! Back to the drawing board!

Java 7, 221 217 180 bytes
void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);}

Loads of bytes saved thanks to @LeakuNun's approach.
Ungolfed & test cases:
Try it here.
class Main{
  void c(char[] s){
    int x = 0,
        y = s.length-1;
    for(char t; x < y; s[x] = s(t, s[y]),
                       s[y] = s(s[y], t),
                       x++,
                       y--){
       t = s[x];
    }
  }

  char s(char a, char b){
    return (char)(64 < a & a < 91
                    ? 96 < b & b < 123
                        ? b-32
                        : b
                    : 64 < b & b < 91
                        ? b+32
                        : b);
  }

  public static void main(String[] a){
    print("Hello, Midnightas");
    print("TEST");
    print("test");
    print("Test");
    print(".,..,,!@");
    print("ABCDefgHijklMNOPqrsTuVWxyz");
    print("AbCdEfGHIJKlmnop123");
  }

  static void print(String s){
    char[] t = s.toCharArray();
    c(t);
    System.out.println(t);
  }
}

Output:
SathginDim ,olleh
q.
TSET
tset
Tset
@!,,..,.
ZYXWvutSrqpoNMLKjihGfEDcba
321pOnMLKJIhgfedcba

You can input and output char[].

@LeakyNun Actually I (believe I) can't in less amount of bytes. It would allow the removal of String a=""; and changed o+= to 0[i]= to save bytes, but Java doesn't have a character .toUpperCase() / .toLowerCase() method, and converting from char to String, use upper/lower method, and then back to char again would require (a lot) more bytes. But feel free to fork the linked ideone and come up with something to make char[] work in less bytes.

180 bytes that can be golfed further (by not modifying it in place).

Sed, 113 + 1 = 114 bytes
Why? Because it's fun to use the wrong tool to do things :P
Usage: Run sed -rf file, enter text and press Ctrl + D (send EOF).
Golfed:
s/[A-Z]/\a\l&/g;s/^.*$/\f&\v/;:x;s/\f\a/\a\f/;s/\a\v/\v\a/;s/\f(.)(.*)(.)\v/\3\f\2\v\1/;tx;s/\f|\v//g;s/\a./\U&/g

Ungolfed:
s/[A-Z]/\a\l&/g #Prepend all upper-case letters with a
                #BEL ASCII character and make them lowercase
s/^.*$/\f&\v/   #Wrap text between a from feed (\f) and a vertical tab (\v)
                #These are used as markers

:x #Define a label named x

s/\f\a/\a\f/;s/\a\v/\v\a/ #Move BEL characters outside of the boundary, so they're not moved later
s/\f(.)(.*)(.)\v/\3\2\1/  #This part does the switching itself
                          #It grabs a character preceded by a form feed and another
                          #one followed by a vertical tab and swaps them, while keeping the text in-between
                          #and replaces the marker \f and \v

tx             #Conditional jump (t) to label x
               #Jumps to the label x if the last substitution (s command) was successful
s/\f|\v//g     #Delete markers
s/\a(.)/\u\1/g #Make letters preceded by a BEL upper-case

Lua, 132 Bytes
function(s)o=""i=0 for m in s:gmatch(".")do n=s:sub(#s-i,#s-i)l=m:lower()o=o..(m==l and n:lower()or n:upper())i=i+1 end print(o)end

There might be a better way to do this in lua, but I think this works.

Ruby, 64 bytes
Try it online!
->s{i=0;s.gsub(/./){c=s[i-=1];$&=~/[A-Z]/?c.upcase: c.downcase}}

Pip, 24 bytes
{b?UCaa}MZLCRVa(_NAZ Ma)

Gets a binary array for the uppercase indices and uppercases those places in the reversed lowercase string.
Try it online!

05AB1E, 9 bytes
Âls€.uÅÏu

Try it online!
Commented:
Â          # Push input and input reversed
 l         # lowercase reversed input
  s        # swap to normal input
   €.u     # map is_upper
      ÅÏ   # where this is true,
           # apply to the reversed input:
        u  # uppercase

Japt, 12 bytes
£ÔgY mvc-X¦v

Try it
£ÔgY mvc-X¦v     :Implicit input of string U
£                :Map each character X at 0-based index Y
 Ô               :  Reverse U
  gY             :  Get the character at index Y
     m           :  Map
      v          :    Literal "v"
       c-        :    Reduce charcode by
         X¦      :      X does not equal
           v     :      Its lowercase
                 :(This results in mapping the character by either "v",
                 : which is Japt's lowercase method or "u",
                 : which is Japt's uppercase method)

Arturo, 62 bytes
$->s[i:0map reverse lower s'c[if<=>s\[i]`A``Z`->upper'c'i+1c]]

Try it
Takes a string, returns a list of characters.

Commodore C64 (just for fun/non-competing), 194 Tokenised BASIC Bytes
To enter this on a real C64, you must use BASIC keyword abbreviations, as you are not able to enter more than 80 characters onto a C64 BASIC line though once entered the interpreter will show the keywords in full. The listing is shown as abbreviations with switched character modes to upper/lower case. You may do this by pressing SHIFT + C=. The program will switch modes anyway on line 0 with the control character N (achieved by pressing CTRL+N after the opening quote).
0input"{CTRL+N}";a$:ifa$=""tHeN
1l=len(a$):dIp(l),b(l):fOx=1tol:p(x)=aS(mI(a$,x,1))>127:nE:i=1:fOx=lto1stE-1
2b(i)=aS(mI(a$,x,1))aN127:i=i+1:nE:fOx=1tol
3ifb(x)>64tH?cH(b(x)-128*p(x));
4ifb(x)<65tH?cH(b(x));
5nE

Note I've marked this as non-competing because whilst the character encoding on the Commodore C64 (PETSCII) is compatible with ASCII, it is not ASCII. As this question is six years old at the time of writing, and the questioner has left, I'm sure no one will mind.
Some caveats, string handling with the INPUT command has some limitations. For instance, if you wanted to enter Hello, World! as a test, you would need to enter it starting with a double quotation mark, so "Hello, World!".
A quick explanation:

Line 0 switches the character set to upper/lower case, rather than PETSCII graphics mode, and waits for a user input; if there is an empty string entered then the program terminates. I added this otherwise it will error, as the FOR/NEXT loops are expecting at least one character to iterate over.
Line 1 will set l to the length of the string, and set up two numeric arrays, called p(l) and b(l). p(l) is used for determines whether the positional character is upper case or not, by checking if the character code is 128 or more. If so, a -1 is added to the array at position x, otherwise it is 0. When that loop ends, we set variable i to 1, and start a new loop counting down from the string length to 1.
Line 2 sets the array b(l) at position i to the PETSCII character code; this value is ANDed with 127 so that each position will be the lower-case character code. i is then incremented by 1 and the loop ends. We then set up a final FOR/NEXT loop, again counting up from 1 to l.
Line 3 checks if array position b(x) is 65 or greater (this is for characters a - z inclusive). If so, it prints the character -128 multiplied by the contents of p(x), which is -1 for upper-case at that position, or 0 if not. -128*-1 will add 128 so converting the character at that position to upper case.
Line 4 checks if array position b(x) has a value below 64; if so, we don't want to convert this to upper case or we will get some odd results for numbers and punctuation etc.
Line 5 iterates the loop again until it is done. When the loop is finished, the program will end gracefully.

The screen shot below shows the BASIC program as the interpreter lists it.
This was a fun challenge and took a little while to get the logic right, so it's quite likely that there are some further optimisations to save some BASIC bytes.

I've just noticed in the screen shot, I took out the sanity check on line 0 with a REM statement. Comment that back in by removing this statement (if you want).

Excel VBA, 256 bytes
Function z(d)
r = Len(d)
ReDim E(1 To r)
For i = 1 To r
b = Mid(d, i, 1)
If Asc(b) > 64 And Asc(b) < 91 Then E(i) = 1
Next i
i = 1
For p = r To 1 Step -1
v = Mid(d, p, 1)
If E(i) = 1 Then z = z & UCase(v) Else z = z & LCase(v)
i = i + 1
Next p
End Function

Google Sheets, 133
Closing parens already discounted.
Input: A1

A2: =LEN(A1)
B1: =ArrayFormula(MID(A1,1+A2-SEQUENCE(A2),1))

Reverse string

C1: =JOIN(,ArrayFormula(if(REGEXMATCH(MID(A1,SEQUENCE(A2),1),"[A-Z]"),UPPER(B:B),LOWER(B:B))))

Compare capital positions, capitalize if originally upper, lower if not. Then join. EXACT(UPPER(...),...) is worse because we're dealing with a range here.
It's a little sluggish because we don't chop off the B:B at the blanks.

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
  char *a,*b,*c;

  a=c=strdup(argv[1]);
  b=&argv[1][strlen(a)-1];
  for(;*a;a++,b--){
    *a=(*a>='A'&&*a<='Z')?((*b>='a'&&*b<='z')?*b-32:*b):((*b>='A'&&*b<='Z')?*b+32:*b);
  }
  puts(c);
  free(c);
  return 0;
}

Input should be taken from stdin.

As this is code-golf please put in the number of bytes this program would cost.

I could reduce it significantly depending on the rules, but I can't find any rules.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

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


text:
Cannonball Conundrum
Your task is to, with an input number p, find the smallest positive cannonball number of order p that is NOT 1.
Definition
A cannonball number (of order p) is a number which is both:

An p-gonal number (See this page).
and an p-gonal pyramid number.

The nth p-gonal pyramid number is the sum of the 1st to nth p-gonal numbers.

(e.g. 4th square pyramid number = 1 + 4 + 9 + 16 = 30)

The picture below represents the 4th square pyramid number, as a square pyramid.

For more info, visit this link.

The cannonball number of order 3, for example, is 10, because it is:

The fourth triangle number (1 + 2 + 3 + 4 = 10)
and the third triangular pyramid number. (1 + 3 + 6 = 10)

Formulas
NOTE: If you can find (or make) more useful formulae than my ones here, please post it here (or message me on the question chat thing).

If you're interested, the formula for the nth p-gonal number is:

And the nth p-gonal pyramid number is:

Specs

p is guaranteed to be larger than 2.
The program must check values for a solution for p up to (and including) 2^16. Your program may do anything if no solutions are found for p.
Only positive indices for n.

Test cases

3 outputs 10 (4th triangle number, 3rd triangle pyramid number)
4 outputs 4900 (70th square number, 24th square pyramid number)

This is code-golf, so shortest answer in bytes wins.
Note: If you do post a solution, please include a description of how the code works.
Should I start a bounty for a solution which is better and doesn't use my formulae?

Could you add some more detail about what a cannonball number is? It's not entirely clear from your description.

Is it guaranteed that there is an answer for any n? If not, what is the range of n you'll be using?

@DrGreenEggsandIronMan Edited to make a definition. n-gonal and n-gonal pyramid numbers shouldn't need defining.

@Geobits Edited to make a range instead of using memory.

Ok, fair warning though: I don't think you're going to find solutions for most n. Even using just n=5, you have to go to 243M to find one (unless I plugged in the wrong formula here).

@DerpfacePython TL;DR: Cannonball numbers quite rare. Look for yourself.

@EᴀsᴛᴇʀʟʏIʀᴋ I know that I'm not guaranteed to have a number for every input. TBH, I had no idea how rare they were until you told me - I can't even find a decent page on them.

@DerpfacePython Let's delete these comments about the sandbox and stuff so a mod doesn't have to, and I would be happy to chat there.

@Geobits, There are solutions to {3, 4, 6, 8, 10, 11, 14, 17, 23, 26, 30, 32, 35, 41, 43, 50, 88}.  I only checked to 100.

I did understand what he means. Took me a while, but I did. My PHP program has 140 bytes.

@Titus Is there any way I can improve my explanation of cannonball numbers?

Wait, how is this question unclear? It seems pretty clear that I want cannonball numbers, and I've explained in-depth what cannonball numbers are.

maybe an explanation of n-gonals an n-pyramidals (or at least links to helpful pages on them). images for n=3 and n=4 would definetely help to understand.

@Titus Chat here.

Can you include a formula for the i'th n-gonal triangular and pyramidal number?

@xnor Yup, got it!

If Geobits was right, then in Python it would be: [0,0,0,10,4900].

not figurative enough yet? For a given n>2 find a number x, so that you can make a) a polygon from x dots that has n sides and b) a pyramid from x spheres based on a polygon of the same shape for n=4: a) x=9 can shape a 3x3 square (polygon with 4 sides) b) x=5 can build a 2x2+1x1 pyramid; it´s a 4-pyramidal (or square pyramidal) number btw: 70*70 is the only solution for n=4 for n=3: triangle numbers are [1, 1+2=3, 3+3=6, 3+4=10, ...] 3-pyramidal numbers are [1, 1+3=4, 4+6=10, ...] x=10 can build a) a triangle of 1+2+3+4 dots and b) a triangular pyramid with 1+3+6 cannonballs

The formula for the nth p-gonal pyramid number should be ((p − 2)n³ + 3n² − (p − 5)n)/6, not ((p − 2)n³ + 3n² + (p − 5)n)/6.

@AndersKaseorg Whup... thanks for catching that!

Do you consider 946 a cannonball number of order 6, since it is the 11th hexagonal pyramid number and the −22nd hexagonal number?

@AndersKaseorg Yep, that would be a cannonball number. I'm pretty sure that's the smallest one as well. NOTE: You mean 22nd not -22nd, right?

@DerpfacePython No I do mean (−22)nd, that’s why it’s a question. You can plug in p = 6, n = −22 to the polygonal number formula and get 946. The question is whether you are including numbers with negative indices.

@AndersKaseorg Ah... in that case, only positive indices are allowed (If n = 22 were plugged in, it would still return 946).

Let us continue this discussion in chat.

Python 3, 129 127 bytes
def f(p):
 x=2
 while 1:
  for i in range(x*x):
   if i//x*((p-2)*i//x+4-p)/2==i%x*(i%x+1)*((p-2)*i%x+5-p)/6==x:return x
  x+=1

A function that takes input via argument and returns the output.
This is an extremely naïve brute force, and takes a very long time for even moderately large p; the execution time will be ridiculous for anything approaching the given maximum for p of 2^16, but there is no reason why the program would not work, given sufficient time.
There are probably far shorter and faster ways of doing this, but I thought it would be good to post something to get this started off.
How it works
The return value x is initialised to 2, and then the program simply loops over all the p-gonal and p-gonal pyramidal numbers up to order x. If the current p-gonal and p-gonal pyramidal numbers, calculated using the formulas, are equal to each other and to x, then x must be the relevant cannonball number and this is returned. Else, x is incremented, and the program tries again for the new value of x.
In terms of golfing, a Cartesian product is used to collapse the two for-loops for the p-gonal and p-gonal pyramidal numbers into a single loop, and the formulas were factorised further to save a few bytes.

Ummm... this might be a bit too late to say... but... my formula was wrong. You just need to change the polygonal formula.

@DerpfacePython Thanks for catching that.

JavaScript, 111 98 bytes
f=n=>{for(b=c=g=1;b++;)for(p=b*(b*3+b*b*(n-2)-n+5)/6;g
{
for(b=2,c=g=1;b<1e6;b++)    // run index b from 2 (to 100k)
    for(
        p=(b*b*3+b*b*b*(n-2)-b*(n-5))/6 // p=the b-th n-pyramidal number
        ;g<p&&c<1e6;c++)   // run while n-gonal is lower than n-pyramidal (and c below 100k)
        if(p==(
            g=(c*c*(n-2)-c*(n-4))/2     // g=the c-th n-gonal number
        )) return p                     // if they are equal, return
}

c is not reinitialized in the inner loop because the next p[b] is definitely larger than the current g[c] (so we have to move on anyway)
examples
samples=[3,4,6,8,10,11,14,17,23,26,30,32,35,41,43,50,88]
for(i in samples) document.write('n='+(n=samples[i])+': '+f(n)+'
');

old PHP program, 115 106 bytes
+16 for current PHP, see below
<?for($b=2;1;$b++)for($p=$b*($b*3+$b*$b*($n-2)-$n+5)/6;$g<$p;++$c)if($p==$g=$c*($c*$n-2*$c-$n+4)/2)echo$p;

loops forever
usage: with PHP<4.2: run from browser with