title: No Quine Built In? No Problem!

text:
# Question
Title: No Quine Built In? No Problem!
# Are you tired of languages with built in quining techniques?

Your challenge, should you choose to accept it, is to add a built-in quine feature to the language of your choice.

### Task

Given some programming language *X*, you should define

1. A **language** *X*′ that is a subset of *X*.
2. A **quine command string** *Q*. (This is a string of your choice; it need not literally be “`Q`”.)

Now you have a new language *Y*, consisting of programs that are in *X*′ except that they may also contain copies of *Q* as if *Q* were a new built-in statement or function. Your job is to implement this language *Y*, by writing

3. A **compiler**, written in *X*′, producing an output program *B* in *X* for each input program *A* in *Y*.

When *B* is run, it should behave like *A* would if all its copies of *Q* had been replaced with a statement in *X* that prints the source code of *B*.

You’ve therefore created a language *Y* that contains a quining builtin *Q*.

### Rules

* Your chosen language subset *X′* must still satisfy the definition of a programming language.
* The output programs *B* of your compiler must be proper quines. You may not use quining builtins that may already be in *X*.
* This is code golf, so the shortest code in bytes (defined as your language's default native encoding) wins.

# Answer
> 3 votes
# CJam, 7 bytes

```
qp":Q~"

```

The quine command string is `Qp":Q~"o`. The language subset is programs that do not use the variable `Q` except as part of the quine command string.

### Demo

Input program:

```
"I am a quine and my source is:
"oQp":Q~"o"
Have a nice day."o

```

Try it online

Output program:

```
"\"I am a quine and my source is:
\"oQp\":Q~\"o\"
Have a nice day.\"o"
:Q~

```

Try it online

Output of output program:

```
I am a quine and my source is:
"\"I am a quine and my source is:
\"oQp\":Q~\"o\"
Have a nice day.\"o"
:Q~
Have a nice day.

```

# Answer
> 1 votes
# Java "only" 498 Bytes

The following java program takes in input as command line arguments.

```
class Q{
public static void main(String[]a){
System.out.println(a[0]);System.out.print("static char[]s={");a[2]+="}static void q(){System.out.print(\""+a[0]+"\\n\");System.out.print(\"static char[]s={\");for(char c:s)System.out.print((int) c+\",\");System.out.print(\"\\b};\\n"+a[1]+"\\n\");for(char c:s)System.out.print(c);System.out.print(\"\\n}\");}";for(char c:a[2].toCharArray())System.out.print((int) c+",");System.out.println("\b};");System.out.println(a[1]);System.out.print(a[2]+"\n}");
}}

```

In this case my language "X" is (a subset of) Java, and my Quine Command string "Q" is q();for each instance of q(); the output program will print its source. Input is restricted to only four lines, and any more or less results in undefined behavior. My golfed program technically follows these same restrictions. So my subset is programs that fit on four lines as shown and do not have a function called q or use any variable named s.

Sample Input

```
class sampleInput{//class def on this line
public static void main(String[]argument){//method header here and optional code although avoid putting code here
System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format YOU MUST! put two braces on the next line*/
}}

```

Sample Output

```
class sampleInput{//class def on this line
static char[]s={83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,72,101,108,108,111,32,87,111,114,108,100,32,79,102,32,81,117,105,110,101,115,34,41,59,113,40,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,92,110,45,45,45,45,45,45,45,45,45,45,45,45,34,41,59,113,40,41,59,47,42,65,118,111,105,100,32,99,111,109,109,101,110,116,115,32,111,110,32,116,104,105,115,32,108,105,110,101,32,117,110,108,101,115,115,32,121,111,117,32,117,115,101,32,116,104,105,115,32,102,111,114,109,97,116,32,112,117,116,32,116,119,111,32,98,114,97,99,101,115,32,111,110,32,116,104,101,32,110,101,120,116,32,108,105,110,101,42,47,125,115,116,97,116,105,99,32,118,111,105,100,32,113,40,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,108,97,115,115,32,115,97,109,112,108,101,73,110,112,117,116,123,47,47,99,108,97,115,115,32,100,101,102,32,111,110,32,116,104,105,115,32,108,105,110,101,92,110,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,115,116,97,116,105,99,32,99,104,97,114,91,93,115,61,123,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,32,99,43,34,44,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,98,125,59,92,110,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,114,103,117,109,101,110,116,41,123,47,47,109,101,116,104,111,100,32,104,101,97,100,101,114,32,104,101,114,101,32,97,110,100,32,111,112,116,105,111,110,97,108,32,99,111,100,101,32,97,108,116,104,111,117,103,104,32,97,118,111,105,100,32,112,117,116,116,105,110,103,32,99,111,100,101,32,104,101,114,101,92,110,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,110,125,34,41,59,125};
public static void main(String[]argument){//method header here and optional code although avoid putting code here
System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format put two braces on the next line*/}static void q(){System.out.print("class sampleInput{//class def on this line\n");System.out.print("static char[]s={");for(char c:s)System.out.print((int) c+",");System.out.print("\b};\npublic static void main(String[]argument){//method header here and optional code although avoid putting code here\n");for(char c:s)System.out.print(c);System.out.print("\n}");}
}

```

# Answer
> 1 votes
# Haskell, 35 bytes

```
main=interact(\s->s++"q="++show s)

```

Includes a trailing newline. The quine command string is `(putStr$q++"q="++show q)`. The language subset is programs with a trailing newline that do not use the variable `q` except as part of the quine command string.

### Demo

Input program:

```
main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."

```

Output program:

```
main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
q="main = do\n  putStrLn \"I am a quine and my source is:\"\n  (putStr$q++\"q=\"++show q)\n  putStrLn \"\\nHave a nice day.\"\n"

```

Output of output program:

```
I am a quine and my source is:
main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
q="main = do\n  putStrLn \"I am a quine and my source is:\"\n  (putStr$q++\"q=\"++show q)\n  putStrLn \"\\nHave a nice day.\"\n"
Have a nice day.

```

---
Tags: code-golf, quine, code-generation
---


title: Leave a Comment

text:
# Question
Title: Leave a Comment
**Task:**

Make a program that leaves a comment on this question. The content should be `1234567890123456`.

**Edits:**

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

# Answer
> 12 votes
## 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}))}

```

# Answer
> 15 votes
# 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

# Answer
> 8 votes
# 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)`.

# Answer
> 3 votes
# 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.

# Answer
> 1 votes
# 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.

---
Tags: code-golf, internet, stack-exchange-api
---


title: Dig to Australia - antipodes

text:
# Question
Title: 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

This is , so the shortest answer in bytes wins!

# Answer
## 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.
> 1 votes

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

```
> 6 votes

# Answer
## 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.
> 6 votes

# Answer
# 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.
> 4 votes

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

```
> 4 votes

# Answer
## 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
> 4 votes

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

```
<table id=out border=1><tr><th>in</th><th>out<th>expected</th><th>ok?</th></tr></table>
<script>
addR=(r,s)=>{var d=document.createElement('td');d.appendChild(document.createTextNode(s));r.appendChild(d)}
test=(x,e,f)=>{var y,r=document.createElement('tr');addR(r,x);addR(r,y=('function'==typeof f)?f(x):f);addR(r,e);addR(r,e.toString()==y.toString()?'Y':'N');document.getElementById('out').appendChild(r)}

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.length)
{
    x=samples.splice(0,8);
    e=samples.splice(0,8);
    test(x,e,h);
    test(e,x,h);
}
</script>

```
> 3 votes

# Answer
# 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 ~~ab~~use 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.
> 2 votes

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

```
> 2 votes

# Answer
# 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};}

```
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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).
> 0 votes

---
Tags: code-golf
---


title: When is Thanksgiving?

text:
# Question
Title: When is Thanksgiving?
# Background

Some holidays have fixed, easy-to-remember dates, like Oct 31, Dec 25, etc. Some, however, want to be troublesome. They're specified as things like "the first Monday in September" or "the fourth Thursday in November". How am I supposed to know when that is?

All I know is that Thanksgiving is fast approaching, so I need a program to help me figure out when it is. Some people even say that it's *tomorrow*, so your program needs to be as short as possible to make sure I can re-type it in time.

# The Challenge

Create a program or function that, given an up-to-four-digit year (e.g. 2015 or 1984), outputs or returns the date of the United States' Thanksgiving in that year. Thanksgiving is defined as the fourth Thursday of November according to the Wikipedia page. *(Hint: that page also includes some interesting information on the date pattern.)*

**Input**: a decimal number with a maximum of four digits representing a year in the Common Era (C.E.). Examples: 987, 1984, 2101

**Output**: the date, including month and day, on which Thanksgiving falls, or would fall if it existed, in that year. This may be in any reasonable format; use your best judgment. Use the Gregorian Calendar in all cases, even if it was not in use at the time.

*(Note: Make sure to handle leap years correctly!)*

**Test cases** Input 1:

```
2015

```

Output 1:

```
Nov 26

```

Input 2:

```
1917

```

Output 2:

```
Nov 22

```

# Scoring

Submissions will be scored in **bytes**. I recommend this website to keep track of your byte count, though you can use any counter you like.

### Bonuses

**-25%** to your score if you handle B.C.E. dates as negative numbers (e.g. -480 would be the year of the battle of Thermopylae).

Negative test case input:

```
-480

```

Corresponding output:

```
Nov 25

```

This is , so the lowest score wins!

Edit: I am marking Thomas Kwa's TI-BASIC submission as accepted. Don't let this discourage you from submitting new entries!

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=64785,OVERRIDE_USER=45162;function answersUrl(e){return"http://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"http://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
# TI-BASIC, 15 bytes * 0.75 = 11.25

*Tested on my TI-84+ calculator*

```
1129-dayOfWk(Ans+ᴇ4,9,1

```

Thankgiving is November 29, minus the day of the week of September 1st, where 1 is Sunday and 7 is Saturday. This outputs in the format `MMDD`.

Test cases: `2015` -\> `1126`, `1917` -\> `1122`, `-480` -\> `1125` have been verified. TI-BASIC seems to use the Gregorian calendar for all dates.

TI-BASIC doesn't support negative years, but this gets the bonus because we add 10000 to the input. Because the Gregorian calendar has a period of 400 years, this doesn't change the day of the week.
> 41 votes

# Answer
## PHP, ~~65~~ ~~48~~ ~~42~~ ~~41~~ 36 (+2 for `-F`) = 38 bytes

```
<?date(Md,strtotime("4thuXI$argn"));

```

Takes input as the first command line argument. Runs with warnings, which are acceptable by our rules. Prints `NovDD`, where `DD` is the day of Thanksgiving.

No online link because ideone doesn't support command line args and I don't know of an online interpreter that does.

Thanks to Alexander O'Mara for teaching me a new trick, and primo for a significant reduction
> 24 votes

# Answer
## Mathematica, ~~59~~ 38 bytes

```
DayRange[{#,11},{#,12},Thursday][[4]]&

```
> 18 votes

# Answer
# JavaScript (ES6), ~~42~~ ~~40~~ 31 bytes - 25% = 23.25

```
a=>28.11-new Date(a,8).getDay()

```

Since the date "may be in any reasonable format", this function uses `DD.MM`. I wrote a TeaScript answer with a different technique, but this formula was shorter.

## Explanation

As the months are zero based, `new Date(a,10)` returns a `Date` object representing November 1 of the specified year.

Since `getDay()` returns a number representing the day of week from `0..6` we want to map from

```
Su Mo Tu We Th Fr Sa
0  1  2  3  4  5  6
to to to to to to to
4  3  2  1  0  6  5

```

then add 22. It turns out that `(11 - new Date(a,10).getDay()) % 7` will do the trick. As @Thomas Kwa pointed out, this is the same as `28-new Date(a,8).getDay()` which is 28 minus the day of the week of September 1.
> 17 votes

# Answer
# Japt, ~~43~~ ~~37~~ ~~36~~ ~~35~~ 29 bytes - 25% = 21.75

**Japt** is a shortened version of **Ja**vaScri**pt**.

```
`{28.11-?w D?e(U,8).getDay()}

```

Hahaha, I found a *really* cheaty trick: the interpreter ignores any brackets inside strings (used to insert code) while decompressing them, so we can compress the entire source code to save a byte \>:D

The two `?`s should be the Unicode unprintables U+0098 and U+0085, respectively. Try it online!

After decompression, the code evaluates to this:

```
"{28.11-new Date(U,8).getDay()}"

```

Which evaluates to:

```
""+(28.11-new Date(U,8).getDay())+""

```

Which gives the proper output.

Uses intrepidcoder's technique, outputting in format `dd.mm`. Properly supports negative years. Suggestions welcome!

**Edit:** As of Dec 2, you can now use this **11-byte** code (scoring **8.25 points**):

```
28.11-ÐU8 e

```

(I so wish I had implemented this sooner!)
> 16 votes

# Answer
# Vitsy, 44 bytes

I'm calculating with *pure mathemagics*!

Golfed:

```
Ve2*V2-V41m+Vaa*Dv1m-Vv4*1m+7M-baa*/+N
/D1M-
```

Ungolfed (moved the method call to the first line to make it readable):

```
Ve2*V2-V4/D1M-+Vaa*Dv/D1M--Vv4*/D1M-+7M-baa*/+N

V         Save the input as a final variable.
 e2*      Push 28 to the stack.
    V         Push the input to the stack.
     2-         Subtract two.
       V4/D1M-        Get floor(input/4).
              +        Add it to the total.
               Vaa*Dv/D1M-          Get floor(input/100), and save 100 as a temp
                                    variable in the process.
                          -          Subtract it from the total.
                           Vv4*/D1M-         Get floor(input/400).
                                    +         Add it to the total.
                                     7M       Modulo by seven.
                                       -       Subtract the result from 28.
                                        baa*/+      Add .11
                                              N      Output as number.
```

There's probably a better algorithm for this (and this is likely horridly golfed), but for those wondering, my algorithm comes from here.

Try it online!

~~Do I get bonus points for calculating it and having exactly 42 bytes?~~ Dreams ruined.

Thanks to @Hosch250 for pointing out I was doing it wrong. :D Fixed.
> 12 votes

# Answer
# JavaScript (ES6), 43.5

Actual byte count is 58. The bonus of -25% applies =\> 58 * 0.75 = **43.5**

```
s=>new Date(s,10,(a=new Date(s,10).getDay())<5?26-a:a+21)

```

Pretty straight ~~and silly~~ way as it could be, without any tricky workarounds or calculations.

De-golf (ES5) + demo:

```
function t(s) {
    a = new Date(s, 10).getDay();
    alert(new Date(s,10,a<=4?26-a:a+21))
}

t(prompt())
```

Note, that entering year 0-100 produces 1900-2000 year. Though, it looks like 0-100 years give the same date as do 1900-2000, judging from the other answers.

---

Replacing `a+18` with `22`, because it's called only in "else", and "else" occurs only if a is neither greater nor less than 4, i.e. exactly 4.

---

Replacing `a<4?26-a:a>4?a+21:22` with `a<=4?26-a:a+21`
> 10 votes

# Answer
# Python, 38 * 0.75 = 28.5 bytes

```
lambda x:28.11-(x-2+x/4-x/100+x/400)%7

```

This works with negative years in the manner specified in the question, although it's come to my attention that there is no year 0 in the Gregorian calendar so this behavior is a bit suspect.
> 10 votes

# Answer
# TeaScript, ~~35~~ ~~33~~ 24 bytes - 25% = 18

```
28.11-new D(x,8).getDay¡

```

This is the same method as my JavaScript answer, which uses Thomas Kwa's clever formula.

### Alternate Version with Explanation

```
r(22,28)F(#/h/t(new D(x,10,l)))+'-11'

r(22,28)    // Range from 22 to 28
        F(    // filter, keeps elements for which the function returns true.
          #    // Expands to function(l,i,a,b)
           /h/    // RegExp literal, Thursday is the only day with an 'h'.
              t(    // test, true if date string contains an 'h'.
                new D(x,10,l) // Create date object
                             ))+'-11' // Append '-11' for the month.

```
> 8 votes

# Answer
## Python, ~~83~~ ~~81~~ 78 bytes

```
from datetime import*
lambda a:'Nov '+`((10-datetime(a,11,1).weekday())%7)+22`

```
* **-2 bytes:** added a name to import (thanks @Κριτικσι Λίθος)
* **-1 bytes:** changed to \*import\** (thanks @FryAmTheEggman)
* **-2 bytes:** changed to repr to convert the day (thanks @willem)
> 5 votes

# Answer
## Excel, ~~367~~ ~~154~~ 53 - 25% = 39.75 bytes

Assumes the year is held in cell A1, in Date format. Returns the integer number of the day in November on which Thanksgiving is held.

This only accounts for normal leap years. It does not account for the fact that the years, 2100, 2200, 2300 are not leap years.

This is only designed to work for 1621 onwards - i.e. since Thanksgiving began being held. (Although it will certainly work all the way back to 0 A.D.).

```
=IF(MOD(YEAR(A1),4)=0,IF(WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,1127-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),1134-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))),IF(WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,1127-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),1134-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))))

```

Pretty-printed:

```
=IF(MOD(YEAR(A1),4)=0,
    IF(WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,
       1127-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),
       1134-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))),
    IF(WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,
       1127-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),
       1134-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))))

```

Gah! Instead of calculating based on the 1st of Jan, then doing lots of leap year calculations to cope with the 29th of Feb, I should have based the calculations on the 1st of Nov. n.b. This now deals correctly with the years 2100, 2200 and 2300, but makes the implementation dependent on your Excel installation's default date format. This version is designed for dd/mm/yyyy:

```
 =IF(WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy"))))<6,
     1127-WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy")))),
     1134-WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy")))))

```

And now that I've done the pfaffing about to get a terse calculation in Smalltalk, backporting it to Excel results in:

```
=DATE(A1,11,MOD(12-WEEKDAY(DATE(9600+A1,11,1)),7)+22)

```

(with the year still in A1, but as an integer). This works even for years 2100, 2200 and 2300, for all dates from 7700BC/E onwards, using Thomas Kwa's date repetition trick.
> 5 votes

# Answer
# Jython, 141 155 Bytes

Uses the Java Calendar and Scanner classes with Python syntax.

```
import java.util.Scanner as s;import java.util.Calendar as c
d=c.getInstance();k=s(System.in);d.set(c.YEAR,k.nextInt());d.set(c.DAY_OF_WEEK,c.THURSDAY)

```

**Edit:** Minor syntax issues, added 14 bytes.

Also see my Brainfuck version.
> 5 votes

# Answer
## PowerShell, ~~67~~ ~~64~~ ~~84~~ ~~72~~ ~~58~~ 45 Bytes

```
param($a)'Nov';28-(date "00$a/9/1").DayOfWeek

```

We take our input integer as `$a`, and immediately output `Nov` and a newline. Then we take `$a` and prepend it with zeroes and September 1st with `00$a/9/1` before generating a new `date` and determining what `DayOfWeek` that is. If September 1st is on a Sunday (`.DayOfWeek` equal to `0`), Thanksgiving is on the 28th. If September 1st is on a Monday (`.DayOfWeek` equal to `1`), Thanksgiving is on the 27th. And so on. Thus, we subtract that day of the week from `28` to output our answer.

Prepending with double-zeroes accounts for single- and double-digit years without interrupting parsing for three- or four-digit years. Doesn't work for negative numbers, as .NET `datetime` doesn't support years less than `0`.

Thanks to TessellatingHeckler and Toby Speight for assistance on this.
> 4 votes

# Answer
# Golfscript, 25 * 0.75 = 18.75 bytes

```
~.4/.25/.4/2---+7%28\--11

```

This uses Sakamoto's formula for the day of the week. Since there are people doing this, the output is in the form of `dd-mm`. My previous submission can be found below:

```
~.4/.25/.4/2---+7%"Nov "28@-

```
> 3 votes

# Answer
# Pyth, ~~30~~ 28 * 75% = 21 bytes

I'm 100% positive that this could be made shorter, but hey, it's my first Pyth program! \o/

```
-28.11%+-+-Q2/Q4/Q100/Q400 7

```

Test suite

Outputs the date in `dd.mm` format.

*Please* suggest ways to golf this if you can! I'd like to learn more about Pyth.
> 3 votes

# Answer
# TSQL, ~~478~~ 296 bytes

Just for funsies. Typically, you'd have a date dimensional table to make this a simple `select * from dimDate where [Year] = @Year and [Holiday] = 'Thanksgiving'` but in the absence of that...

```
create function a(@y varchar(4))returns date as begin declare @d date,@i int=0 set @d=convert(date,@y+'-11-01')declare @t table(d date,c int identity)while @i<28 begin if datepart(weekday,@d)=5 insert @t(d) select @d select @d=dateadd(d,1,@d),@i+=1 end select @d=d from @t where c=4 return @d end

```

Ungolfed:

```
if exists(select * from sys.objects where name='a' and [type]='FN') drop function a
go

create function a(@y varchar(4))returns date
-- select dbo.a('2015')
as
begin
    declare @d date,@i int=0;

    set @d=convert(date,@y+'-11-01'); -- cannot golf out dashes for dates <year 1000

    declare @t table(d date,c int identity)

    while @i<28
    begin -- populate "November" array
        if datepart(weekday,@d)=5 insert @t(d) select @d -- assumes @@datefirst = 7
        select @d=dateadd(d,1,@d),@i+=1
    end;

    select @d=d from @t where c=4

    return @d

end

```
> 3 votes

# Answer
# Excel, ~~64~~ 48

Year in A1

~~=DATE(A1,11,CHOOSE(WEEKDAY(DATE(A1,11,1)),26,25,24,23,22,28,27))~~

```
=DATE(A1,11,MOD(12-WEEKDAY(DATE(A1,11,1)),7)+22)

```
> 2 votes

# Answer
## Befunge, 41 Bytes

```
47*&:::4"d"*/\"d"/-\4/++5+7%-" voN",,,,.@

```

Run on this interpreter.

**Explanation:** A common year is *365 = 1 mod 7* days, so the year plus every 4th year, minus every 100th (`d` in ascii) year, plus every 400th years accounts for any leap days (including the present year). The result of `:::4"d"*/\"d"/-\4/++` can then be thought of as March 5th, the first day after February to fall on the same day as the first day of the year in common years. After that we calibrate to the pattern with `5+7%-` subtracting a number of days of the week from the 28th(the `47*`stored earlier) of November. Then print.

A version correcting for B.C. years is currently longer than the bonus provides for, at 59 -25% = 44.25 bytes:

```
47*&v
!`0:<+*"(F"_v#
" voN",,,,.@>:::4"d"*/\"d"/-\4/++5+7%-

```
> 2 votes

# Answer
## Matlab, 78 bytes

```
x=find(all(bsxfun(@eq,datestr(datenum(input(''),11,1:30),'ddd'),'Thu')'));x(4)

```
> 2 votes

# Answer
# Ruby, ~~60~~ ~~58~~ ~~42.75~~ 39 * 0.75 = 29.25 bytes

```
->y{puts"Nov #{28-Time.new(y,9).wday}"}

```

**42.75 bytes**

```
->y{puts"Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"}

```

**58 bytes**

```
->y{puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"}

```

**60 bytes**

```
->y{puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11,1).wday]+21}"}

```

Ungolfed:

```
-> y {
  puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"
}

```

Tests:

```
->y{puts"Nov #{28-Time.new(y,9).wday}"}.(2015)
Nov 26

->y{puts"Nov #{28-Time.new(y,9).wday}"}.(1917)
Nov 22

->y{puts"Nov #{28-Time.new(y,9).wday}"}.(-480)
Nov 25

```
> 2 votes

# Answer
# PHP 5.3+, 59 bytes

This uses PHP builtin function `strtotime` to parse the date.

```
<?=gmdate('M d',strtotime("Next Thursday $_GET[Y]-11-19"));

```

This expects the value to be passed over GET parameter `Y` **OR** over `php-cli Y=<year>`.

It tries to find the next thursday after 19th November.
So far, with the tests I've made, it works fine.

Be aware that 2-digit years may be interpreted differently.

I use `gmdate` to avoid timezone issues, but it works equally well using `date` (at least, where I live).
> 1 votes

# Answer
# GNU coreutils, 35 bytes

```
seq -f$1-11-2%g 2 8|date -f-|grep h

```

Simply searches the week 22-28 November for a Thursday. Run it in a C or POSIX locale, as I depend on Thursday being the only day abbreviation to contain a 'h'.

---

Here's a cleverer answer, albeit a byte longer:

```
echo Nov $((28-`date -d$1-5-5 +%w`))

```

We retrieve the day-of-week number of a date in a fairly arbitrary week between March and September (so day and month are one digit each, and we're not affected by a possible leap day). We pick the day so that it's a Sunday (`%w==0`) when Thanksgiving is on the 28th. We can then subtract that value from 28 to obtain the appropriate Thursday.
> 1 votes

# Answer
## Smalltalk - Squeak and Pharo, ~~69~~ ~~57~~ ~~54~~ ~~49~~ ~~35~~ ~~34~~ ~~33~~ 32 - 25% = 24 bytes

**"Nov nn": ~~69B~~ 49B (-25% = 36.75B)**
**11nn (anInt): ~~57~~ ~~54~~ 32B (-25% = 24B)**

```
"Year supplied as an integer value, y
 Result provided as an integer value, 11nn
 Methods Date>>y:m:d: and >>w created as duplicates
 of year:month:day and weekdayIndex"
(12-(Date y:y m:11d:1)w)\\7+1122

```

Previous versions

**11nn output**

```
"Year supplied as an integer value, y
 Result provided as an integer value, 11nn"
(12-(Date year:y month:11 day:1) weekdayIndex)\\7+1122

"Year supplied as an integer value, y
 Result provided as an integer value, d, prefixed by 11"
d:=(12-(Date year:y month:11 day:1) weekdayIndex)\\7+1122

```

**Nov nn output**

```
"Year supplied as an integer value, y  Result provided as a string, 'Nov nn'"
'Nov ', (12-(Date year:y month:11 day:1) weekdayIndex\\7+22) asString

```

**nn output**

```
"Year supplied as an integer value, y  Result provided as an integer value, d"
d:=(12-(Date year:y month:11 day:1) weekdayIndex)\\7+22

```

n.b. This is provided as a program - specifically a Workspace expression - rather than as a method.

It assumes the input is a given (as per the phrasing "given an up-to-four-digit year".
Including the declaring and giving of the input would add another 11 characters:

`|y|y:=2015.(12-(Date y:y m:11 d:1)w)\\7+1122`

Thanks to eMBee, for showing how to remove yet one more char - the whitespace immediately before the 'w'.

Actually, that inspired me to try removing the whitespace before 'd:' :
`|y|y:=2015.(12-(Date y:y m:11d:1)w)\\7+1122`
Which worked!
> 0 votes

# Answer
# Pike, ~~87 91 107 77~~ 76 bytes - 25% = 57

```
string t(int y){return"Nov "+((11-Calendar.Day(y,11,1)->week_day())%7+22);}

```

leaving the old one in for comparison because i find it more clever in terms of taking advantage of the Calendar module, but the above is way shorter.

```
string t(int y){object n=Calendar.Month(y,11);return"Nov "+(n->weeks()->day(4)&n->days())[3]->month_day();}

```
> 0 votes

# Answer
# VBA, 124 bytes * 75% = 93 bytes

```
Function e(y)
For i = 1 To 7
x = DateSerial(y, 11, 21) + i
If Weekday(x) = 5 Then e = Format(x, "mmm dd")
Next
End Function

```

I'm not sure if spaces count, it's somewhere between 102 and 124, feel free to edit.
If integers are a valid output I'm more than happy to remove the `Format` part.
> 0 votes

# Answer
# T-SQL ~~215 bytes~~ 248 * 0.75 = 186 bytes

```
create function t(@y int)returns table return select x=convert(char(6),x,107)from(select x=cast(dateadd(dd,d,dateadd(yy,@y-2015+7600,'20151101'))as date)from(select d=21+n from(values(0),(1),(2),(3),(4),(5),(6))b(n))c)t where datepart(weekday,x)=5

```

Ungolfed

```
set nocount on;
if object_id('dbo.t') is not null drop function dbo.t
go

create function t(@y int)returns table return
    select x=convert(char(6),x,107)
    from (
        select
        x=cast(dateadd(dd,d,dateadd(yy,@y-2015+7600,'20151101'))as date)
        from (
            select d=21+n
            from (values (0),(1),(2),(3),(4),(5),(6))b(n)
        )c
    )t
    where datepart(weekday,x)=5
go

```

which with this test scaffold

```
select
  [ 2015 = Nov. 26]=(select x from dbo.t( 2015))
 ,[ 1917 = Nov. 22]=(select x from dbo.t( 1917))
 ,[ 1752 = Nov. 23]=(select x from dbo.t( 1752))
 ,[ 1582 = Nov. 25]=(select x from dbo.t( 1582))
 ,[ 1400 = Nov. 27]=(select x from dbo.t( 1400))
 ,[ -480 = Nov. 25]=(select x from dbo.t( -480))
 ,[-5480 = Nov. 28]=(select x from dbo.t(-5480))
;
go

```

yields as desired

```
2015 = Nov. 26  1917 = Nov. 22  1752 = Nov. 23  1582 = Nov. 25  1400 = Nov. 27  -480 = Nov. 25 -5480 = Nov. 28
--------------- --------------- --------------- --------------- --------------- --------------- ---------------
Nov 26          Nov 22          Nov 23          Nov 25          Nov 27          Nov 25          Nov 28

```
> 0 votes

# Answer
# TSQL, ~~53~~ 52 bytes

```
DECLARE @ CHAR(4)=2000

PRINT DATEADD(d,59,DATEDIFF(d,1,DATEADD(m,9,@))/7*7)

```

**Fiddle**

Calculating monday before or on september 2nd and adding 59 days

(better than calculating monday before or on october 4th and adding 31 days because october is the 10th month thus saving 1 byte)
> 0 votes

# Answer
## Perl, 92 bytes

```
use Time::Local;(localtime(timelocal 0,0,0,$_,10,$ARGV[0]))[6]==4?print "Nov $_":0for 22..28

```

EDIT : Fixed output format, fixed bug e.g. 2012 result, used shorter "for" format. Thanks to msh210.
> -1 votes

---
Tags: code-golf, date
---


title: Determine the winner of a game of War

text:
# Question
Title: Determine the winner of a game of War
The card game War is interesting in that the final outcome is entirely determined by the initial arrangement of the deck, so long as certain rules are followed for the order in which cards are picked up from the playing field and moved to decks. In this challenge, there will only be 2 players, simplifying things greatly.

## The Game

1. Each player is dealt a deck of 26 cards.
2. Each player places the top card in their deck face-up. The player with the higher-ranking card (`Ace > King > Queen > Jack > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2`) wins the round, and places their card on top of their opponent's card, flips them over, and adds them to the bottom of their deck (so their winning card is on the bottom of the deck, and the other player's losing card is just above it). This is done until one of the players runs out of cards.
    * If the cards are of equal rank, then each player places the top 2 cards of their deck face-up on top of their previous card (so that the card that was on top of the deck is the second card in the stack, and the card that was second-from-top is on top). Then, the ranks (of the top card of each stack) are compared again, and the winner places their entire stack on top of the loser's entire stack, turns the stack upside-down, and places it on the bottom of their deck. If there is another tie, more cards are played in the same way, until a winner is chosen or one player runs out of cards.

If at any point one of the players needs to draw a card from their deck, but their deck is empty, they immediately lose the game.

## The Challenge

Given two lists of cards in the players' decks, in any convenient format, output a truthy value if Player 1 wins, and a falsey value if Player 2 wins.

For convenience, a 10 card will be represented with a `T`, and face cards will be abbreviated (`Ace -> A, King -> K, Queen -> Q, Jack -> J`), so that all cards are one character long. Alternatively, ranks may be represented with decimal integers 2-14 (`Jack -> 11, Queen -> 12, King -> 13, Ace -> 14`) or hex digits 2-E (`10 -> A, Jack -> B, Queen -> C, King -> D, Ace -> E`). Since suits don't matter, suit information will not be given.

* You may assume that all games will terminate at some point (though it may take a very long time), and one player will always run out of cards before the other.
* Each player places cards simultaneously, and one card at a time, so there is never any ambiguity about which player ran out of cards first.

## Test Cases

The test cases use `23456789ABCDE` to represent the ranks (in ascending order).

```
D58B35926B92C7C4C7E8D3DAA2, 8E47C38A2DEA43467EB9566B95 -> False
669D9D846D4B3BA52452C2EDEB, E747CA988CC76723935A3B8EA5 -> False
5744B95ECDC6D325B28A782A72, 68394D9DA96EBBA8533EE7C6C4 -> True
87DB6C7EBC6C8D722389923DC6, E28435DBEBEA543AA47956594A -> False
589EAB9DCD43E9EC264A5726A8, 48DC2577BD68AB9335263B7EC4 -> True
E3698D7C46A739AE5BE2C49286, BB54B7D78954ED526A83C3CDA2 -> True
32298B5E785DC394467D5C9CB2, 5ED6AAD93E873EA628B6A4BC47 -> True
B4AB985B34756C624C92DE5E97, 3EDD5BA2A68397C26CE837AD48 -> False
9A6D9A5457BB6ACBC5E8D7D4A9, 73E658CE2C3E289B837422D463 -> True
96E64D226BC8B7D6C5974BAE32, 58DC7A8C543E35978AEBA34D29 -> True
C2978A35E74D7652BA9762C458, 9A9BB332BE8C8DD44CE3DE66A5 -> False
BEDB44E947693CD284923CEA82, 8CC3B75756255A683A6AB9E7DD -> False
EEDDCCBBAA8877665544332299, EEDDCCBBAA9988776655443322 -> False
EEDDCCBBAA9988776655443322, DDCCBBAA9988776655443E3E22 -> True

```

## Reference Implementation

This reference implementation is written in Python 3, and takes input in the same format as the test cases (except separated by a newline instead of a comma and a space).

```
#!/usr/bin/env python3

from collections import deque

p1, p2 = [deque(s) for s in (input(),input())]
print(''.join(p1))
print(''.join(p2))

try:
    while p1 and p2:
        p1s = [p1.popleft()]
        p2s = [p2.popleft()]
        while p1s[-1] == p2s[-1]:
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
        if p1s[-1] > p2s[-1]:
            p1.extend(p2s+p1s)
        else:
            p2.extend(p1s+p2s)
except IndexError:
    pass
finally:
    print(len(p1) > 0)

```

# Answer
## JavaScript (ES6), 134 bytes

```
f=([p,...r],[q,...s],t=[],u=[],v)=>!q||p&&(v|p==q?f(r,s,[...t,p],[...u,q],!v):p>q?f([...r,...u,q,...t,p],s):f(r,[...s,...t,p,...u,q]))
```

```
<div oninput=o.checked=f(p.value,q.value)>
Player 1's cards: <input id=p><br>
Player 2's cards: <input id=q><br>
<input id=o type="checkbox"> Player 2 loses
```

Return `undefined` if Player 2 wins, `true` otherwise. Accepts comparable iterators, usually arrays of integers or strings of hex characters. Answer is composed of over 22% of `.` characters, which I think must be a record for me.
> 4 votes

# Answer
# Python, 160 (155?) bytes

```
f=lambda x,y,z=1:f(*((x,y,z+2),(x[z:]+y[:z]+x[:z],y[z:]),(x[z:],y[z:]+x[:z]+y[:z]))[(x[z-1]>y[z-1])+(x[z-1]<y[z-1])*2])if len(y)>z<len(x)else len(x)>len(y)

```

This solution is theoretically valid, but it require the default python maximum recursion depth to be increased for some of the test cases.

The second solution is 5 bytes longer, but work for all the test cases.

```
f=lambda x,y,z=1:(f(x,y,z+2)if x[z-1]==y[z-1]else f(x[z:]+y[:z]+x[:z],y[z:])if x[z-1]>y[z-1]else f(x[z:],y[z:]+x[:z]+y[:z]))if len(y)>z<len(x)else len(x)>len(y)

```

Edit: Ungolfed solution 1:

```
def f(x,y,z=1):
    if len(y)<z>len(x):
        return len(x)>len(y)
    else:
        return f(*(
            (x,y,z+2),
            (x[z:],y[z:]+x[:z]+y[:z]),
            (x[z:]+y[:z]+x[:z],y[z:])
        )[(x[z-1]>y[z-1])+(x[z-1]<y[z-1])*2])

```
> 4 votes

# Answer
# Python, 261 to 265 bytes

```
def f(a,b):
 if a==""or b=="":return b==""
 p=a[0];q=b[0];a=a[1:];b=b[1:]
 if p>q:a+=q+p
 if p<q:b+=p+q
 while p[-1]==q[-1]:
  if len(a)<2 or len(b)<2:return len(b)<2
  v=a[1];w=b[1];p+=a[0:2];q+=b[0:2];a=a[2:];b=b[2:]
  if v>w:a+=q+p
  if v<w:b+=p+q
 return f(a,b)

```

As posted, this is 265 bytes and it works in both Python 2 and Python 3. You can save 4 bytes in Python 2 by replacing the spaces with a single tab in the while loop.

Try it online
> 2 votes

# Answer
# Haskell, 372

My first Haskell Program

(It's my first functional programming, too...)

```
w[]_=False
w _[]=True
w a b=if length j==0 then a>b else w (drop(d$head j)a++fst(head j))(drop(d$head j)b++snd(head j))where j=p a b
d(a,b)=quot(maximum[length a,length b])2
f (Just a)=a
p a b=map f$filter(/=Nothing)[t(a!!x,take(x+1)a,b!!x,take(x+1)b)|x<-[0,2..minimum[length a,length b]-1]]
t(a,b,c,d)=if a==c then Nothing else if a>c then Just(d++b,[])else Just([],b++d)

```

I'd love to have tips on how to improve.

Usage:

```
w "D58B35926B92C7C4C7E8D3DAA2" "8E47C38A2DEA43467EB9566B95"
w "669D9D846D4B3BA52452C2EDEB" "E747CA988CC76723935A3B8EA5"
w "5744B95ECDC6D325B28A782A72" "68394D9DA96EBBA8533EE7C6C4"
w "87DB6C7EBC6C8D722389923DC6" "E28435DBEBEA543AA47956594A"
w "589EAB9DCD43E9EC264A5726A8" "48DC2577BD68AB9335263B7EC4"
w "E3698D7C46A739AE5BE2C49286" "BB54B7D78954ED526A83C3CDA2"
w "32298B5E785DC394467D5C9CB2" "5ED6AAD93E873EA628B6A4BC47"
w "B4AB985B34756C624C92DE5E97" "3EDD5BA2A68397C26CE837AD48"
w "9A6D9A5457BB6ACBC5E8D7D4A9" "73E658CE2C3E289B837422D463"
w "96E64D226BC8B7D6C5974BAE32" "58DC7A8C543E35978AEBA34D29"
w "C2978A35E74D7652BA9762C458" "9A9BB332BE8C8DD44CE3DE66A5"
w "BEDB44E947693CD284923CEA82" "8CC3B75756255A683A6AB9E7DD"
w "EEDDCCBBAA8877665544332299" "EEDDCCBBAA9988776655443322"
w "EEDDCCBBAA9988776655443322" "DDCCBBAA9988776655443E3E22"

```

Haskell is quick... :)

```
real    0m0.039s
user    0m0.022s
sys     0m0.005s

```
> 2 votes

---
Tags: code-golf, string, game, card-games, decision-problem
---


title: Domain Name Appraisal

text:
# Question
Title: Domain Name Appraisal
Domain name trading is big business. One of the most useful tools for domain name trading is an automatic appraisal tool, so that you can easily estimate how much a given domain is worth. Unfortunately, many automatic appraisal services require a membership/subscription to use. In this challenge, you will write a simple appraisal tool that can roughly estimate the values of .com domains.

## Input / Output

As input, your program should take a list of domain names, one per line. Each domain name will match the regex `^[a-z0-9][a-z0-9-]*[a-z0-9]$`, meaning that it is composed of lowercase letters, digits, and hyphens. Each domain is at least two characters long and neither begins nor ends with a hyphen. The `.com` is omitted from each domain, since it is implied.

As an alternative form of input, you can choose to accept a domain name as an array of integers, instead of a string of characters, as long as you specify your desired character-to-integer conversion.

Your program should output a list of integers, one per line, which gives the appraised prices of the corresponding domains.

## Internet and Additional Files

Your program may have access to additional files, as long as you provide these files as part of your answer. Your program is also allowed to access a dictionary file (a list of valid words, which you don't have to provide).

(Edit) I have decided to expand this challenge to allow your program to access the internet. There are a couple restrictions, being that your program cannot look up the prices (or price histories) of any domains, and that it only uses pre-existing services (the latter to cover up some loopholes).

The only limit on total size is the answer size limit imposed by SE.

### Example input

These are some recently-sold domains. Disclaimer: Although none of these sites seem malicious, I do not know who controls them and thus advise against visiting them.

```
6d3
buyspydrones
arcader
counselar
ubme
7483688
buy-bikes
learningmusicproduction

```

### Example Output

These numbers are real.

```
635
31
2000
1
2001
5
160
1

```

## Scoring

Scoring will be based on "difference of logarithms." For example, if a domain sold for $300 and your program appraised it at $500, your score for that domain is abs(ln(500)-ln(300)) = 0.5108. No domain will have a price less than $1. Your overall score is your average score for the set of domains, with lower scores better.

To get an idea what scores you should expect, simply guessing a constant `36` for the training data below results in a score of about `1.6883`. A successful algorithm has a score less than this.

I chose to use logarithms because the values span several orders of magnitude, and the data will be filled with outliers. The use of absolute difference instead of difference squared will help reduce the effect of outliers in scoring. (Also, note that I am using the natural logarithm, not base 2 or base 10.)

## Data Source

I have skimmed a list of over 1,400 recently sold .com domains from Flippa, a domain auction website. This data will make up the training data set. After the submission period is over, I will wait an additional month to create a test data set, with which the submissions will be scored. I might also choose to collect data from other sources to increase the size of the training/test sets.

The training data is available at the following gist. (Disclaimer: Although I have used some simple filtering to remove some blatantly NSFW domains, several might still be contained in this list. Also, **I advise against visiting any domain you don't recognize**.) The numbers on the right-hand side are the true prices. https://gist.github.com/PhiNotPi/46ca47247fe85f82767c82c820d730b5

Here is a graph of the price distribution of the training data set. The x-axis the the natural log of price, with y-axis being count. Each bar has a width of 0.5. The spikes on the left correspond to $1 and $6 since the source website requires bids to increment at least $5. The test data may have a slightly different distribution.

Here is a link to the same graph with a bar width of 0.2. In that graph you can see spikes at $11 and $16.

# Answer
> 3 votes
# Perl, 1.38605

I figured I should go ahead and post my own submission, in the hope that it spurs competition. Its score of `1.38605` means that it is typically off by a factor of `3.999` (that was my stopping point). I didn't use any machine learning libraries, just straight up Perl. It does require access to a dictionary; I used the one from here.

Please feel free to use some of the numbers/statistics from my program in your own.

```
use strict;

my %dict;
my $dictname = "dict.txt";
open(my $dfh, '<', $dictname);
while (my $row = <$dfh>) {
  chomp $row;
  $dict{lc $row} = 1;
}

my $domain = <>;
chomp($domain);

my $guess = 1;

if($domain =~ /^[a-z]*$/){
    my @bylength = (200000,20001,401,45,45,41,26,26,26,26,26,24);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 18;
  }
} elsif ($domain =~ /^[0-9]*$/){
  my @bylength = (300000,30001,6000,605,50);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 7;
  }
} elsif ($domain =~ /^[a-z0-9]*$/){
  my @bylength = (52300,523,28);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 23;
  }
} else {
  my @bylength = (50000,500,42,32,32,31);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 12;
  }
}

my $wordfact = 1;

my $leftword = 0;
for(my $i = 1; $i <= length($domain); $i++){
  my $word = substr $domain, 0, $i;
  if(exists($dict{$word})){
    $leftword = $i;
  }
}

$wordfact *= ($leftword/length($domain))**2 * 0.8 + ($leftword/length($domain)) * -0.1 + 0.9;

if($leftword/length($domain) >= 0.8){
  $wordfact *= 2.4;
}

my $rightword = 0;
for(my $i = 1; $i <= length($domain); $i++){
  my $word = substr $domain, length($domain)-$i, $i;
  if(exists($dict{$word})){
    $rightword = $i;
  }
}

$wordfact *= ($rightword/length($domain))**2 * 0.9 + ($rightword/length($domain)) * -0.2 + 1;

$guess *= $wordfact;

my $charfact = 1;
my %charfacts = (
  i => 1.12, #500
  l => 0.84,
  s => 1.09,
  a => 0.94,
  r => 1.03,
  o => 0.97,
  c => 1.22, #400
  d => 0.88,
  u => 1.07,
  t => 0.95,
  e => 1.08,
  m => 0.91, #300
  p => 1.08,
  y => 0.92,
  g => 0.97,
  ne => 0.56, #100
  n => 1.13,
  z => 0.67,
  re => 1.30,
  es => 0.75,
);
while(my ($key,$value) = each %charfacts){
  if($domain =~ /$key/){
    $charfact *= $value;
  }
}
$guess *= $charfact;

$guess = int($guess + 0.5);
if($guess <= 0){
  $guess = 1;
}

print $guess;

```

Here's a graph made by my scoring program, showing a scatter plot of appraisal over actual price and a histogram of the errors. In the scatter plot `.:oO@` mean `10, 20, 30, 40, 50` domains at that point, respectively. In the histogram each `O` represents 16 domains.

The scale is set at `1 character width = e^(1/3)`.

There are three main steps to this program. The results from each step are multiplied together.

1. Categorization by character class and length. It determines if the domain is all letters, all numbers, letters and numbers, or if it contains a hyphen. It then gives a numerical value determined by the domain's length. I found that there is a strange dip in value around length 5. I suspect this is due to sampling: shorter domains are valuable due to their length (even if the letters are nonsense), while most longer domains tend to be words/phrases. I order to prevent overfitting, I put a restriction in that domains cannot be penalized for being shorter (so length 5 is at least as good as length 6).
2. Evaluation of word content. I use the dictionary to determine the lengths of the left-hand and right-hand words in a domain name. For example, `myawesomesite -> my & site -> 2 & 4`. Then, I try to do some fitting based on what proportion of the domain name is made up by those words. Low values typically indicate that the domain does not contain a word, contains a pluralized/modified word not in the dictionary, contains a word surrounded by other characters (internal words are not detected, although I tried that with no improvement), or contains a several-word phrase. High values indicate that it is a single word or a likely a two word phrase.
3. Evaluation of character content. I looked for substrings that were contained in lot of domains and which appeared to affect the values of the domain. I believe this is caused by certain types of words being more popular/more attractive, for various reasons. For example, the letter `i` appeared in about half of the domains (741 of them), and bumps up domain value by about 12% on average. That's not overfitting; there's something real there, that I don't fully understand. The letter `l` appears in 514 domains and has a factor of 0.84. Some of the less common letters/digraphs, like `ne` which appeared 125 times and has a really low factor of 0.56, might be overfitting.

In order to improve upon this program, I would probably need to use machine learning of some kind. Also, I could look for relationships between length, word content, and character content to find better ways of combining those separate results into the overall appraisal value.

---
Tags: string, code-challenge, internet, test-battery
---


title: Expand a bash brace expansion

text:
# Question
Title: Expand a bash brace expansion
For mostly historical reasons, bash is quite a hodge-podge of syntax and programming paradigms - this can make it awkward and sometimes frustrating to golf in. However it does have a few tricks up its sleeve that can often make it competitive with other mainstream script languages. One of these is brace expansion.

There are two basic types of brace expansion:

* List braces may contain comma-separated lists of arbitrary strings (including duplicates and the empty string). For example `{a,b,c,,pp,cg,pp,}` will expand to `a b c pp cg pp` (note the spaces around the empty strings).
* Sequence braces may contain sequence endpoints separated by `..`. Optionally another `..` may follow, followed by a step size. Sequence endpoints may be either integers or characters. The sequence will automatically ascend or descend according to which endpoint is greater. For example:
    + `{0..15}` will expand to `0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`
    + `{-10..-5}` will expand to `-10 -9 -8 -7 -6 -5`
    + `{3..-6..2}` will expand to `3 1 -1 -3 -5`
    + `{a..f}` will expand to `a b c d e f`
    + `{Z..P..3}` will expand to `Z W T Q`

Beyond this, sequence and list braces may exist with list braces:

* `{a,b,{f..k},p}` will expand to `a b f g h i j k p`
* `{a,{b,c}}` will expand to `a b c`

Braces expand with non-whitespace strings either side of them. For example:

* `c{a,o,ha,}t` will expand to `cat cot chat ct`

This also works for multiple braces concatenated together:

* `{ab,fg}{1..3}` will expand to `ab1 ab2 ab3 fg1 fg2 fg3`

This can get quite complex. For example:

* `{A..C}{x,{ab,fg}{1..3},y,}` will expand to `Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C`

However, if there is whitespace between expansions, then they simply expand as separate expansions. For example:

* `{a..c} {1..5}` will expand to `a b c 1 2 3 4 5`

Note how order is always preserved.

---

Entries for this challenge will expand bash brace expansions as described above. In particular:

* eval by `bash` (or other shells that perform similar expansion) is not allowed
* sequence braces will always be number-to-number, lowercase-to-lowercase or uppercase-to-uppercase with no mixing. Numbers will be integers in the 32-bit signed range. If given, the optional step size will always be a positive integer. *(Note that bash will also expand `{A..z}` as well, but this may be ignored for this challenge)*
* individual items in list braces will always be composed only of upper- and lower-case alphanumeric characters (empty string included)
* list braces may contain arbitrary nestings of other brace expansions
* braces may be concatenated arbitrary numbers of times. This will be limited by your language's memory, so the expectation is that you can theoretically do arbitrary numbers of concatenations but if/when you run out of memory that won't count against you.

The examples in the text above serve as testcases. Summarised, with each line of input corresponding to the same line of output, they are:

### Input

```
{0..15}
{-10..-5}
{3..-6..2}
{a..f}
{Z..P..3}
{a,b,{f..k},p}
{a,{b,c}}
c{a,o,ha,}t
{ab,fg}{1..3}
{A..C}{x,{ab,fg}{1..3},y,}
{a..c} {1..5}
{a{0..100..10},200}r

```

### Output

```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-10 -9 -8 -7 -6 -5
3 1 -1 -3 -5
a b c d e f
Z W T Q
a b f g h i j k p
a b c
cat cot chat ct
ab1 ab2 ab3 fg1 fg2 fg3
Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C
a b c 1 2 3 4 5
a0r a10r a20r a30r a40r a50r a60r a70r a80r a90r a100r 200r

```

# Answer
# Ruby, ~~405~~ ~~403~~ ~~401~~ 400 bytes

A wise man (Jamie Zawinski) once said, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."

I don't think I fully appreciated that quote until I tried to solve this problem with recursive regex. Initially, the regex cases seemed simple, until I had to deal with the edge cases involving letters adjacent to brackets, and then I knew that I was in hell.

Anyways, run it online here with test cases

```
->s{s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i
$1[/\d/]?0:(a,b=x,y)
k=a<b ?[*a..b]:[*b..a].reverse
?{+0.step(k.size-1,$4?c:1).map{|i|k[i]}*?,+?}}
r=1
t=->x{x[0].gsub(/^{(.*)}$/){$1}.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/).map{|i|i=i[0];i[?{]?r[i]:i}.flatten}
r=->x{i=x.scan(/({(\g<1>)*}|[^{} ]+)/).map(&t)
i.shift.product(*i).map &:join}
s.split.map(&r)*' '}

```

Ungolfed:

```
->s{
  s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){  # Replace all range-type brackets {a..b..c}
    x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i     # Set up int variables
    $1[/\d/]?0:(a,b=x,y)                    # Use int variables for a,b if they're numbers
    k=a<b ?[*a..b]:[*b..a].reverse          # Create an array for the range in the correct direction
    '{'+                                    # Return the next bit surrounded by brackets
      0.step(k.size-1,$4?c:1).map{|i|k[i]   # If c exists, use it as the step size for the array
      }*','                                 # Join with commas
      +'}'
  }
  r=1                                       # Dummy value to forward-declare the parse function `r`
  t=->x{                                    # Function to parse a bracket block
    x=x[0].gsub(/^{(.*)}$/){$1}             # Remove outer brackets if both are present
                                            # x[0] is required because of quirks in the `scan` function
    x=x.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/)
                                            # Regex black magic: collect elements of outer bracket
    x.map{|i|i=i[0];i[?{]?r[i]:i}.flatten   # For each element with brackets, run parse function
  }
  r=->x{                                    # Function to parse bracket expansions a{b,c}{d,e}
    i=x.scan(/({(\g<1>)*}|[^{} ]+)/)        # Regex black magic: scan for adjacent sets of brackets
    i=i.map(&t)                             # Map all elements against the bracket parser function `t`
    i.shift.product(*i).map &:join          # Combine the adjacent sets with cartesian product and join them together
  }
  s.split.map(&r)*' '                       # Split on whitespace, parse each bracket collection
                                            #   and re-join with spaces
}

```
> 3 votes

# Answer
# Python 2.7, ~~752~~ 728 bytes

Wow, this is like a bunch of code golfs in one challenge!

Thanks to @Neil for shortening a lambda

```
def b(s,o,p):
 t,f=s>':'and(ord,chr)or(int,str);s,o=t(s),t(o);d=cmp(o,s)
 return list(map(f,range(s,o+d,int(p)*d)))
def e(s):
 c=1;i=d=0
 while c:d+=-~'{}}'.count(s[i])%3-1;i+=1;c=i<len(s)and 0<d
 return i
def m(s):
 if len(s)<1:return[]
 if','==s[-1]:return m(s[:-1])+['']
 i=0
 while i<len(s)and','!=s[i]:i+=e(s[i:])
 return[s[:i]]+m(s[i+1:])
n=lambda a,b:[c+d for c in a for d in b]or a or b
def p(s):
 h=s.count
 if h('{')<1:return[s]
 f,l=s.index('{'),e(s)
 if h('{')<2and h('..')>0and f<1:s=s[1:-1].split('..');return b(s[0],s[1],s[2])if len(s)>2 else b(s[0],s[1],1)
 if f>0 or l<len(s):return n(p(s[:f]),n(p(s[f:l]),p(s[l:])))
 return sum(map(list,map(p,m(s[1:-1]))),[])
o=lambda s:' '.join(p('{'+s.replace(' ',',')+'}'))

```

### Explanation

* `b`: calculates range according to specs.
* `e`: returns position of first outermost close brace. Iterative.
* `m`: splits outermost elements on commas. Recursive.
* `n`: combines arrays while checking for empties. ~~I couldn't get `and/or` to work.~~
* `p`: Where most of the work is done. Checks all the cases (Range, just list, needs to combine). Recursive.
* `o`: What should take input. Formats input/output to `p`.

---

I feel I can improve in some places, so I will try to golf more. Also I should put in more detail in the explanation.
> 2 votes

# Answer
## JavaScript (Firefox 30-57), ~~465~~ ~~427~~ 425 bytes

```
f=s=>/\{/.test(s)?f(s.replace(/([^,{}]*\{[^{}]*\})+[^,{}]*/,t=>t.split(/[{}]+/).map(u=>u.split`,`).reduce((a,b)=>[for(c of a)for(d of b)c+d]))):s.split`,`.join` `
s=>f(`{${s.split` `}}`.replace(/\{(-?\w+)\.\.(-?\w+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{m=(a>'@')+(a>'_');a=parseInt(a,m?36:10);o=parseInt(o,m?36:10);e=+e||1;if(o<a)e=-e;for(r=[];e<0?o<=a:a<=o;a+=e)r.push(m?a.toString(36):a);r=`{${r}}`;return m-1?r:r.toUpperCase()}))

```

ES6 version of `f` weighs in at an extra 10 bytes:

```
f=s=>/\{/.test(s)?f(s.replace(/([^,{}]*\{[^{}]*\})+[^,{}]*/,t=>t.split(/[{}]+/).map(u=>u.split`,`).reduce((a,b)=>[].concat(...a.map(c=>b.map(d=>c+d)))))):s.split`,`.join` `
g=s=>f(`{${s.split` `}}`.replace(/\{(-?\w+)\.\.(-?\w+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{m=(a>'@')+(a>'_');a=parseInt(a,m?36:10);o=parseInt(o,m?36:10);e=+e||1;if(o<a)e=-e;for(r=[];e<0?o<=a:a<=o;a+=e)r.push(m?a.toString(36):a);r=`{${r}}`;return m-1?r:r.toUpperCase()}))
h=(s,t=s.replace(/\{[^{}]*\}/,""))=>s!=t?h(t):!/[{}]/.test(s)
```

```
<input oninput="o.textContent=h(this.value)?g(this.value):'{Invalid}'"><div id=o>
```

Explanation: Starts by changing spaces into commas and wrapping the entire string in `{}` for consistency (thanks to @Blue for the idea). Then searches for all the `{..}` constructs and expands them into `{,}` constructs. Next uses recursion to repeatedly expands all `{,}` constructs from the inside out. Finally replaces all commas with spaces.

```
f=s=>/\{/.test(s)?                  while there are still {}s
 f(s.replace(                       recursive replacement
  /([^,{}]*\{[^{}]*\})+[^,{}]*/,    match the deepest group of {}s
  t=>t.match(/[^{}]+/g              split into {} terms and/or barewords
   ).map(u=>u.split`,`              turn each term into an array
   ).reduce((a,b)=>                 loop over all the arrays
    [for(c of a)for(d of b)c+d]))   cartesian product
  ):s.split`,`.join` `              finally replace commas with spaces
s=>f(                               change spaces into commas and wrap
 `{${s.split` `}}`.replace(         match all {..} seqences
   /\{([-\w]+)\.\.([-\w]+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{
    m=(a>'@')+(a>'_');              sequence type 0=int 1=A-Z 2=a-z
    a=parseInt(a,m?36:10);          convert start to number
    o=parseInt(o,m?36:10);          convert stop to number
    e=+e||1;                        convert step to number (default 1)
    if(o<a)e=-e;                    check if stepping back
    for(r=[];e<0?o<=a:a<=o;a+=e)    loop over each value
     r.push(m?a.toString(36):a);    convert back to string
    r=`{${r}}`;                     join together and wrap in {}
    return m-1?r:r.toUpperCase()})) convert type 1 back to upper case

```
> 2 votes

---
Tags: code-golf, string
---


title: Diamond with numbers

text:
# Question
Title: Diamond with numbers
Inspired by **this**, print an ascii diamond pattern built using `0-9`.

**Rules**

* Input `n` should be between `0-9`, anything outside that range is undefined
* The diamond should be padded with spaces
* The middle line should always have no padding and be the only line to contain `n`, in the center
* Print to stdout
* As always, this is

**Test Cases**

* n = 0

```
0

```
* n = 1, print

```
 0
010
 0

```
* n = 2, print

```
  0
 010
01210
 010
  0

```
* n = 9, print

```
         0
        010
       01210
      0123210
     012343210
    01234543210
   0123456543210
  012345676543210
 01234567876543210
0123456789876543210
 01234567876543210
  012345676543210
   0123456543210
    01234543210
     012343210
      0123210
       01210
        010
         0

```

# Answer
> 2 votes
# Vitsy, 50 bytes

I don't think I'm done golfing yet!

```
VVHr1mV{V2*1+\[2m]
:Xru
v&VvD([D\[' 'O]]-H1ml\NaOY

```

Explanation:

```
VVHr1mV{V2*1+\[2m]
V                  Pop n, set n as the global final variable (GFV).
 V                 Push the GFV to the current stack.
  H                Pop n, pop o, push each item of the range from o to n.
   r               Reverse the current program stack.
    1m             Call the method on line index 1.
      V{           Push the GFV to the bottom of the current stack.
        V2*1+      Push the GFV*2+1 to the stack.
             \[  ] Pop n, do the stuff in brackets n times.
               2m  Call the method on line index 2. Note that this is necessary due
                   to an unknown bug.

:Xru
:                  Clone the current stack, pushing a second stack to the stack
                   stack and jumping to it.
 X                 Pop n and discard.
  r                Reverse the current stack.
   u               Pop the current stack and concatenate it to the previous.

v&VvD([D\[' 'O]]-H1ml\NaOY
v                  Pop n, save as a temporary variable.
 &                 Push a new stack to the stack stack and jump to it.
  V                Push the GFV.
   v               Push the temp var, clear the temp var memory.
    D([        ]   If the top item is not zero, do the stuff in brackets.
                   This is necessary as all loops always apply once.
       D\[' 'O]    Peek n, output n spaces.
   -               Pop n, pop o, push o-n.
    H              Pop n, pop o, push each item of the range from o to n.
     1m            Call the method at line index 1.
       l\N         Output all numbers in this stack.
          aO       Output a newline.
            Y      Pop and discard the current stack from the stack stack.

```

Try it online!

---
Tags: code-golf, ascii-art
---


title: Normal sentences

text:
# Question
Title: Normal sentences
Write a program or function which, given an input string and a standard deviation `σ`, outputs that string along the normal distribution curve with mean `0` and standard deviation `σ`.

### Normal distribution curve

The `y` coordinate of each character `c` is:

where `σ` is given as input, and where `x` is the `x` axis coordinate of `c`.

* The character in the center of the string has `x = 0`. If the string's length is even, either of the two middle characters can be chosen as the center.
* Characters are separated by steps of `0.1` (e.g. the character to the left of the center one has `x = -0.1`, the one to the right of the middle one has `x = 0.1`, etc.).

### Printing the string

* Lines, like characters, are separated by steps of `0.1`.
* Each character is printed on the line with the `y` value that is closest to its own `y` value (if the value is precisely in between the values of two lines, choose the one with the biggest value (just like how `round` usually returns `1.0` for `0.5`)).
* For example, if the `y` coordinate of the center value (i.e. the maximum value) is `0.78` and the `y` coordinate of the first character is `0.2`, then there will 9 lines: the center character being printed on line `0` and the first character being printed on line `8`.

### Inputs and outputs

* You may take both inputs (the string and `σ`) as program arguments, through `STDIN`, function arguments or anything similar in your language.
* The string will only contain printable `ASCII` characters. The string can be empty.
* `σ > 0`.
* You may print the output to `STDOUT`, in a file, or return it from a function (**as long as** it is a string and not say a list of strings for each line).
* A trailing new line is acceptable.
* Trailing spaces are acceptable as long as they don't make the line exceed the last line in length (so no trailing space is acceptable on the last line).

### Test cases

```
σ    String

0.5  Hello, World!

     , W
   lo   or
  l       l
 e         d
H           !

0.5  This is a perfectly normal sentence

                tly
              ec    n
             f       o
            r         r
           e           m
          p             a
        a                l
      s                    se
This i                       ntence

1.5  Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers.

                                                d answer site for p
                                      uestion an                   rogramming
                      Code Golf is a q                                        puzzle enthusia
Programming Puzzles &                                                                        sts and code golfers.

0.3  .....................

          .
         . .

        .   .

       .     .

      .       .

     .         .
    .           .
   .             .
...               ...

```

### Scoring

This is ,

```
                 nsw
                a   er
              t
             s         i
            e           n
           t
         or               by
       sh                   te
so the                        s wins.

```

# Answer
> 2 votes
# Python 3 with SciPy, ~~239~~ 233 bytes

```
from scipy import stats,around,arange
def f(s,t):
 l=len(t);p=[];y=around(stats.norm.pdf((arange(l)-l//2)*.1,scale=s),1)*10
 for i in range(l):p+=[[' ']*(max(y)-y[i])];p[i]+=[t[i]]+[' ']*(y[i]-y[0])
 for j in zip(*p):print(*j,sep='')

```

A function that takes input via argument of standard deviation `s` and string `t`, and prints the result to STDOUT.

**How it works**

```
from scipy import stats,around,arange  Import the statistics, rounding and range functions
                                       from SciPy
def f(s,t):                            Function with input standard deviation s and string
                                       t
l=len(t);p=[]                          Define the much-used length of t as l and initialise
                                       the print values list p
arange(l)                              Generate a list of integer x values in [0,l)...
...-l//2*.1                            ...and scale such that 0 is at the middle character
                                       and the x-step is 0.1
stats.norm.pdf(...,scale=s)            Generate a list containing the y values for each x
                                       value by calling the normal probability
                                       density function scaled with s...
y=around(...,1)                        ...round all values to 1 decimal place...
...*10                                 ...and multiply by 10 to give the vertical index of
                                       each character
for i in range(l):...                  For all characters in t...
p+=[[' ']*(max(y)-y[i])]               ..add the number of lines below the character as
                                       spaces...
p[i]+=[t[i]]+[' ']*(y[i]-y[0])         ...add the character and the number of lines above
                                       the character as spaces

This leaves p containing a list for each desired output line, but transposed.

for j in zip(*p):...                   For every output line in the transpose of p...
print(*j,sep='')                       ...print the output line

```

Try it on Ideone

# Answer
> 2 votes
## Ruby: ~~273~~ 254 Bytes

```
->n,s{j,o,g,r,l=-(n.size/2),[],0,{}
n.gsub(/./){(r[((2*Math::PI)**-0.5*10*Math.exp(-(j/1e1)**2/2/s/s)/s).round]||="")<<$&
j+=1}
r.sort.map{|y, c|o<<(l ?$/*(y-l-1):"")+(" "*g)+(c[0,(h=c.size)/2])+(" "*(n.size-g*2-h))+(c[h/2,h])
g+=h/2
l=y}
puts o.reverse}

```

A huge thanks to Kevin Lau for saving 18 bytes!

---
Tags: code-golf, math, string
---