# Question
Title: Capitalize first letter of each word of input
This is a relatively quick one, but I'm sure you'll like it.

Codegolf a program that will take input in the form of a sentence and then provide the output with the first letter capitalized in each word.

Rules:

1. Submissions may not be in the form of a function. So no:

`function x(y){z=some_kind_of_magic(y);return z;}` as your final answer... Your code must show that it takes input, and provides output.
2. The code must preserve any other capital letters the input has. So

```
eCommerce and eBusiness are cool, don't you agree, Richard III?

```

will be rendered as

```
ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?

```
3. Some of you may be thinking, "Easy, I'll just use regex!" and so using the native regex in your chosen golfing language will incur a 30 character penalty which will be applied to your final code count. *Evil laugh*
4. A "word" in this case is anything separated by a space. Therefore `palate cleanser` is two words, whereas `pigeon-toed` is considered one word. `if_you_love_her_then_you_should_put_a_ring_on_it` is considered one word. If a word starts with a non-alphabetical character, the word is preserved, so `_this` after rendering remains as `_this`. (Kudos to Martin Buttner for pointing this test case out).

* 4b. There is no guarantee that words in the input phrase will be separated by a single space.
5. Test Case, (please use to test your code):

Input:

```
eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye

```

Output:

```
ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye

```
6. This is code golf, shortest code wins...

Good luck...

# Answer
> 22 votes
# CJam, ~~15~~ 13 bytes

```
Lq{_eu?_S-}/;

```

Try it online in the CJam interpreter.

### Pseudocode

```
L             e# B := ""
 q            e# Q := input()
  {       }/  e# for C in Q:
   _eu?       e#     C := B ? C : uppercase(C)
       _S-    e#     B := string(C).strip(" ")
            ; e# discard(B)

```

All modified characters C are left on the stack and, therefore, printed when exiting.

# Answer
> 13 votes
# CSS 2.1, 49

```
:after{content:attr(t);text-transform:capitalize}

```

**Explanation**:

* The `attr` function takes the input from a `t` (text) HTML attribute.
* The input is capitalized by setting `text-transform` to `capitalize`.
* The output is provided as a generated content, using the `content` property on an `::after` pseudo-element.

**Runnable snippet**:

```
:after {
    content: attr(t);
    text-transform: capitalize;
}
```

```
<div t="eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye"></div>
```

**Note**: CSS 2.1 specified the desired behavior: `capitalize` uppercased the first character of each word. However, CSS3 uppercases first typographic letter unit of each word. So the snippet above won't work properly neither on old IE, which didn't follow CSS 2.1; nor on new compliant browsers which follow CSS3.

# Answer
> 11 votes
# Perl, 13 bytes

```
perl -040pe '$_="\u$_"'

```

9 bytes plus 4 bytes for `040p` (assuming I've interpreted the rules on special invocations correctly).

`-040` sets the input record separator `$/` to a single space, so spaces are preserved; the `\u` escape sequence converts the next character to title case.

# Answer
> 10 votes
# Javascript (*ES6*), 77 bytes

```
alert(prompt().split(' ').map(x=>x&&x[0].toUpperCase()+x.slice(1)).join(' '))
```

### Commented

```
alert( // output
    prompt(). // take input
    split(' '). // split by spaces
    map(x=> // map function to array
        x && // if x, empty string "" is falsey and returns itself
        x[0].toUpperCase() + x.slice(1) // capaitalize 1st char and concatenate the rest
    ).
    join(' ') // join array with spaces
)

```

# Answer
> 8 votes
# Perl Version \< 5.18, 30 27 26 25

```
say map"\u$_",split$,=$"

```

`24` characters `+1` for `-n`.

`\u` makes the next character in a string uppercase. @ThisSuitIsBlackNot pointed this out to save 1 byte. Before we were using the function `ucfirst`.

From the perldocs,

> As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a literal string composed of a single space character (such as ' ' or "\x20" , but not e.g. / / ). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/ ; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern / / instead of the string " " , thereby allowing only a single space character to be a separator. In earlier Perls this special case was restricted to the use of a plain " " as the pattern argument to split, in Perl 5.18.0 and later this special case is triggered by any expression which evaluates as the simple string " " .

Since `$"` evaluates to a space, this will preserve the spaces. Since we want to both set `$,` to a space character, and input a space character to the split, @nutki pointed out we can do both as the input to the split. That saves 3 bytes from what we had before, which was first setting `$,` and then inputting `$"` to the split.

Using a `,` for map instead of `{}` saves an additional byte, as @alexander-brett pointed out.

Run with:

```
echo 'eCommerce     rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye' | perl -nE'say map"\u$_",split$,=$"'

```

# Answer
> 7 votes
# CJam, ~~17~~ 15 bytes

```
lS/{S+(eu\+}/W<

```

Test it here.

Fairly straightforward implementation of the spec. Make use of the new `{}&` to avoid errors for consecutive spaces.

*Two bytes saved by Dennis.*

# Answer
> 7 votes
## C, ~~64~~ 63 bytes

```
a;main(c){while(~(c=getchar()))putchar(a?c:toupper(c)),a=c-32;}

```

*Fix: some compilers (such as Clang) don't like an int parameters in place of argv, so I moved it to a global variable. The byte count stays the same. Thanks to squeamish ossifrage for noticing.* *Down to 63 bytes, thanks Dennis.*

Ungolfed:

```
int a;

int main(int c) {
    while(~(c = getchar()))
        putchar(a ? c : toupper(c)),
        a = c - ' ';
}

```

Pretty straightforward: if a is false, the character is converted to uppercase. It is set after reading a space: c - ' ' is false only if c == ' '. toupper() ignores everything that is not a lowercase letter, so symbols and multiple spaces are fine. -1 has all bits set, so when getchar() returns -1 the NOT operator makes it zero, and the loop stops. a is declared as a global variable, so it is initializd to zero (false). This ensures that the first word is capitalized.

# Answer
> 7 votes
# Python 3, ~~59~~ 56 bytes

```
f=1
for c in input():print(end=f*c.upper()or c);f=c==" "

```

Thanks to @Reticality for 3 bytes.

# Answer
> 5 votes
# JAVA, 273 bytes

**EDIT**

```
import static java.lang.System.*;class x{public static void main(String[] s){char[] a=new java.util.Scanner(in).nextLine().toCharArray();boolean f=1>0;for(int i=0;i<a.length;i++){if(a[i]==' '){f=1>0;continue;}if(f){a[i]=Character.toUpperCase(a[i]);f=1<0;}}out.println(a);}}

```

# Answer
> 5 votes
# \>\<\> (Fish), 39 bytes

```
</?-' 'o:;?(0:<-*' '*('{'$)'`'::i
i/.0e

```

Method:

* Take one char and capitalize it if in range `a-z` then print it out. (left-to-right code for this part is `i::'backquote')$'{'(*' '*+`)
* **If** the last taken char is an EOF char **then** exit **else** print it
* **If** the last taken char is a space char **then** go to point 1 **else** take a new letter and go to point 2.

# Answer
> 5 votes
## JavaScript (regex solution) - 104 bytes

Someone has to bite the bullet and post the RegEx solution! 74 characters, plus the +30 character penalty:

```
alert(prompt().replace(/(^| )[a-z]/g,function(m){return m.toUpperCase()}))

```

Or if you want to read and understand the code in its non-compacted fashion:

```
//     Matches the (beginning of the line or a space), followed by a lowercase English character.
string.replace( /(^| )[a-z]/g ,
                function(match) { return match.toUpperCase(); }

```

# Answer
> 5 votes
# Vim, ~~11~~, 10 bytes

```
qqvUW@qq@q

```

Explanation:

```
qq           #Start recording in register 'q'
  vU        #Make the character under the cursor uppercase
     W       #Move forward a WORD
      @q     #recursively call macro 'q'
        q    #stop recording
         @q  #Call the recursive macro

```

Do I get a gold-badge for outgolfing Dennis?

# Answer
> 5 votes
# brainfuck, ~~342~~ 310 bytes

```
>-[-[-<]>>+<]>-[->+>>>>+<<<<<]>[-<+>],[<[->>+>+<<<]>>>[-<<<+>>>]<<[->>+>+<<<]>>>[-<<<+>>>]<<[->-<]>>+<[>->>>+[+[<]>>+<+]>[-<<<<<<->>>>>>]<<<+++++[>+++++<-]>+>>+<<[<<<<[->+>>+<<<]>[-<+>]>>[[-]>>+<<]>>-[<<<[-<<<<->>>>]>>>+>-<]<<<<<->>>>-]>>[-<<<<[-]>>>>]<<<<<<[-]]>[->[-]<<<<<[->>>+>>+<<<<<]>>>[-<<<+>>>]>]<<<.,]

```

Try it online!

Explanation:

```
[
* Many constants were taken from the BF constants page on esolangs.org.
*
* Cells:
*
* true number: the true index of the cell
* fake number: the relative cell index as referenced in the code
*
* true# | fake# | info
*   0       -     Used only for initialization of (fake) cell 0
*   1       -     Used only for initialization of (fake) cell 0
*   2       -     Used only for initialization of (fake) cell 0
*   3       -     Used only for initialization of (fake) cell 0
*   4       0     Holds constant 32 / ' ', which is used for cell 5 (space flag) and for subtracting (' ') from input
*   5       1     Holds the input/output char during the main loop. Also used in setup for copying cell 0 to cell 5
*   6       2     Used to hold 32 / ' ' (temporarily, to subtract it from the input)
*   7       3     Used to hold a copy of the input that gets mangled throughout the loop, being subtracted from to
*                 check what the input character was. Also used in space code to copy cell 0 to cell 5.
*   8       4     Used primarily as a flag to decide which part of the space/not space conditional to run (if 1, the
*                 space code runs; if 0, the not-space code runs). Also used when copying cell 3 to 6 (for checking
*                 if cell 3 == 0), and to copy cell 1 to 3 (input).
*   9       5     Holds the 'space flag' (different from cell 4). When a space is encountered, this cell is set to 32
*                 ('a' - 'A'). When a lowercase character is encountered, this cell is subtracted cell 1 (input),
*                 clearing it by default (subtraction without copying implicitly clears the cell). This makes it so
*                 that only the first character after a space is converted to uppercase.
*   10      6     Used as a temporary cell when initializing constants 65 ('a' - ' ') and 2, also used in the
*                 lowercase check loop to set cell 8 (cell 3 == 0 flag)
*   11      7     Used as the counter in the lowercase check loop, goes from 26 to 0 (decrementing each iteration).
*                 Also used as a temporary cell when initializing constant 65.
*   12      8     Used to hold (cell 3 == 0) flag, which subtracts cell 5 from cell 1 if it is 1 (which means that
*                 cell 1 is a lowercase letter).
*   13      9     Used as a flag to figure out if the else branch of the lowercase checker should run. If one, the
*                 character is not a lowercase letter or space and so cell 5 is cleared.
]

>-[-[-<]>>+<]>-    set cell 0 to 32 (=' ')

[->+>>>>+<<<<<]    set cells 1 and 5 to 32 (end on 0)
>[-<+>]            move 1 back to 0 (end on 1)

,[                 loop over input (cell 1)

    copy cell 0 to cell 2
    <[->>+>+<<<]     [move cell 0 to cells 2 and 3 (end on 0)]
    >>>[-<<<+>>>]    [move cell 3 back to cell 0 (end on 3)]

    copy cell 1 to cell 3
    <<[->>+>+<<<]    [move cell 1 to cells 3 and 4 (end on 1)]
    >>>[-<<<+>>>]    [move cell 4 back to cell 1 (end on 4)]

    <<[->-<]         [subtract cell 2 from cell 3 (end on 2)]

    >                cell 3 / input minus ' '

    >+<              set cell 4 as flag to run space code if set (end on 3)

    [                not space branch (check if in lowercase zone)
        >-                 clear cell 4 (end on 4)

        >>>+[+[<]>>+<+]>   set cell 9 to 65 (='a' minus ' ') (uses 6 7 8 as tmp) (end on 9)

        [-<<<<<<->>>>>>]   [subtract cell 9 from cell 3 (end on 9)]

        [need to check if cell 3 is from 0-26, it could be above and not a lowercase letter]

        <<<                cell 6
        +++++[>+++++<-]>+  set cell 7 to 26
        >>+<<              set cell 9 to 1 (end on 7)

        [                  do 26 times

            <<<<                   cell 3
            [->+>>+<<<]            [move cell 3 to cell 4 and 6 (end on 3)]
            >[-<+>]                [move cell 4 back to cell 3 (end on 4)]

            >>                     cell 6

            [[-]>>+<<]             [if cell 6 is set, set cell 8 to 1 (end on 6)]

            >>-                    decrement cell 8 (if cell 3 was not zero cell 8 is now zero) (if cell 3 was zero cell 8 is now 255)

            [                      if cell 3 is zero (start here on 8)
                <<<                    cell 5
                [-<<<<->>>>]           [sub cell 5 from cell 1 (end on 5)]

                >>>+                   clear cell 8 (end on 8)
                >-<                    set cell 9 to 0 (end on 8)
            ]

            <<<<<-                 decrement cell 3 (end on 3)
            >>>>-                  end on 7 and decrement
        ]

        >>[                cell 9 set (else branch so we have no lowercase letter)
            -                  [clear cell 9]

            <<<<               cell 5
            [-]                [clear cell 5]
            >>>>               cell 9
        ]

        <<<<<<             cell 3
        [-]                [clear cell 3]
    ]

    >                cell 4
    [                space branch
        -                      clear cell 4 (end on 4)

        >[-]                   clear cell 5 (space flag/may have been set)
        <<<<<[->>>+>>+<<<<<]   [set space flag (cell 5) (coincidentally, it is also 32 so we can copy from cell 0) (0-> 5 and 3) (end on 0)]
        >>>[-<<<+>>>]          [3 to 0 (end on 3)]

        >                      end on 4
    ]

    <<<.             from 4 to 1 (output 1)
,]

```

# Answer
> 4 votes
# Python 2, 73 bytes

```
i=raw_input()
print''.join((c,c.upper())[p==' ']for p,c in zip(' '+i,i))

```

This program capitalises a letter if preceded by a space (with a kludge for the first character in the string). It relies on the `.upper()` string method to capitalise correctly.

# Answer
> 4 votes
# PHP 64 ~~76~~ ~~77~~ ~~83~~ ~~84~~ ~~89~~ bytes

Does `$_GET` count as input in PHP?
If so, here is my first CG attempt

```
foreach(explode(' ',$_GET[@s])as$k=>$v)echo$k?' ':'',ucfirst($v)

```

Thanks manatwork :)

One could just use the `ucwords` function, which would result in 21 bytes:

```
<?=ucwords($_GET[@s])

```

thanks Harry Mustoe-Playfair :)

# Answer
> 4 votes
# Haskell, 69

```
import Data.Char
main=interact$tail.scanl(!)' '
' '!c=toUpper c;_!c=c

```

### Explanation:

`scanl` takes a function `(a -> b -> a)` and an initial value `a`, then iterates over a list of `[b]`s to make a list of `[a]`s:

```
scanl (!) z [a,b,c] == [   z
                       ,   z ! a
                       ,  (z ! a) ! b
                       , ((z ! a) ! b) ! c]

```

It repeatedly takes the **previous result** as the **left argument** of the function passed to it, and a **value from the input list** as the **right argument**, to make the next one.

I wrote a function `(!) :: Char -> Char -> Char` that returns the right character you pass it, but capitalizes it if the left char is `' '` (space). For `scanl`, this means: return the **value from the input list**, but capitalize it if the **previous result** was a space. So `scanl (!) ' ' "ab cd"` becomes:

```
    scanl (!) ' ' "ab cd"
==> ' ' : scanl (!) (' ' ! 'a') "b cd"
==> ' ' : scanl (!)     'A'     "b cd"
==> ' ' : 'A' : scanl (!) ('A' ! 'b') " cd"
==> ' ' : 'A' : scanl (!)     'b'     " cd"
==> ' ' : 'A' : 'b' : scanl (!) ('b' ! ' ') "cd"
==> ' ' : 'A' : 'b' : scanl (!)     ' '     "cd"
==> ' ' : 'A' : 'b' : ' ' : scanl (!) (' ' ! 'c') "d"
==> ' ' : 'A' : 'b' : ' ' : scanl (!)     'C'     "d"
==> ' ' : 'A' : 'b' : ' ' : 'C' : scanl (!) ('C' ! 'd') ""
==> ' ' : 'A' : 'b' : ' ' : 'C' : scanl (!)     'd'     ""
==> ' ' : 'A' : 'b' : ' ' : 'C' : 'd' : ""
==> " Ab Cd"

```

We need the initial value `' '` to capitalize the first letter, but then we chop it off with `tail` to get our final result.

# Answer
> 3 votes
# Pyth, 20 bytes

```
uXGHr@GH1fqd@+dzTUzz

```

These multiple spaces really sucks. Otherwise there would have been a really easy 12 bytes solution.

Try it online: Pyth Compiler/Executor

### Explanation

```
                      implicit: z = input string
         f       Uz   filter [0, 1, 2, ..., len(z)-1] for elements T, which satisfy:
          qd@+dzT        " " == (" " + z)[T]
                      (this finds all indices, which should be capitalized)
u                  z  reduce, start with G = z, for H in idices ^ update G by
 XGH                     replace the Hth char of G by
    r   1                upper-case of
     @GH                 G[H]
                      implicitly print result

```

edit: 16 chars is possible with @Dennis algorithm.

# Answer
> 3 votes
# PHP: ~~76~~ 74 characters

```
foreach($l=str_split(fgets(STDIN))as$c){echo$l?ucfirst($c):$c;$l=$c==" ";}

```

Sample run:

```
bash-4.3$ php -r 'foreach($l=str_split(fgets(STDIN))as$c){echo$l?ucfirst($c):$c;$l=$c==" ";}' <<< 'eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye'
ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye

```

# Answer
> 3 votes
# JAVA, 204 ~~211~~ ~~226~~ bytes

My first entry on CG, I hope it's fine:

```
class U{public static void main(String[]s){int i=0;char[]r=s[0].toCharArray();r[0]=Character.toUpperCase(r[0]);for(char c:r){if(c==' '&&i>0)r[i+1]=Character.toUpperCase(r[i+1]);i++;System.out.print(c);}}}

```

Saved 7 bytes thanks to @TNT

# Answer
> 3 votes
# CJam, 14 bytes

It's not the shortest, but...

```
qS/Sf.{\eu}s1>

```

Another answer using similar ideas:

```
qS/Laf.{;eu}S*

```

`.x` only changes the first item if one of the parameters has only one item.

# Answer
> 3 votes
# Lua, ~~64~~ ~~62~~ 61 bytes

Lua is a horrendous language to golf in, so I'm pretty proud of myself for this one.

```
print(string.gsub(" "..io.read(),"%s%l",string.upper):sub(2))

```

~~\[Try it here\]~~ Outdated, will update tommorow

# Answer
> 3 votes
# C, 74 bytes

```
a,b=1;main(){while((a=getchar())>0)b=isspace(putchar(b?toupper(a):a));}

```

Makes no assumptions about the run-time character set (ASCII, EBCDIC, Baudot, ...whatever). Does assume that EOF is negative (I think C guarantees that).

```
a,b=1;
main()
{
    while((a=getchar())>0)
        b=isspace(putchar(b?toupper(a):a));
}

```

a is the input character; b is true if the last character was space. The only non-obvious bit is that we use the fact that `putchar` returns the character printed if there's no error.

# Answer
> 3 votes
# C# Linq - 187

This is nowhere close to winning but I just love Linq too much.

```
namespace System{using Linq;class P{static void Main(string[]a){Console.Write(a[0].Substring(1).Aggregate(a[0][0].ToString().ToUpper(),(b,c)=>b[b.Length-1]==32?b+char.ToUpper(c):b+c));}}}

```

# Answer
> 3 votes
# Java 8, 135 bytes

It's rare that I beat all the other answers that use the same language.

```
interface M{static void main(String[]a){int c=0;for(char i:a[0].toCharArray()){System.out.print(c==0?(i+"").toUpperCase():i);c=i-32;}}}

```

TIO

# Answer
> 2 votes
# Bash, 61

```
a="${@//: / }"
a=(${a//: / })
a="${a[@]^}"
echo "${a//:/ }"

```

Note the colons are simply to make the program display OK here. In reality these can be some non-printable character, such as BEL.

### Output

```
$ ./cap1st.sh "eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye"
ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
$

```

---

# Bash, 12

Sadly this one doesn't preserve leading/mutliple/trailing spaces, but otherwise it works:

```
echo "${@^}"

```

### Output

```
$ ./cap1st.sh eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye
ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
$

```

# Answer
> 2 votes
## C#, ~~133~~ 131

```
using C=System.Console;class P{static void Main(){var s=2>1;foreach(var c in C.ReadLine()){C.Write(s?char.ToUpper(c):c);s=c==32;}}}

```

# Answer
> 2 votes
# Pip, 15 + 1 for `-s` = 16

```
{IaUC:a@0a}Ma^s

```

Explanation:

```
                  a is first cmdline arg (implicit)
            a^s   Split a on spaces
{         }M      Map this function to each element:
 Ia                 If the word is not empty,
   UC:a@0             uppercase its first character
         a          Return the word
                  Output the resulting list (implicit) joined on spaces (-s flag)

```

One interesting feature of Pip that this program draws on is the `:` assignment meta-operator. Most C-like languages have some set of compute-and-assign operators: e.g. `x*=5` does the same thing as `x=x*5`. In Pip, however, you can tack `:` onto *any* operator and turn it into a compute-and-assign operator. This even goes for unary operators. So `-:x` computes `-x` and assigns it back to `x`, the same as `x:-x` would. In this case, `UC:` is used (together with Pip's mutable strings) to uppercase the first character of a word.

The program takes input from the command-line, requiring an invocation like this:

```
python3 pip.py -se "{IaUC:a@0a}Ma^s" "test teSt TEST  _test"

```

# Answer
> 2 votes
# JavaScript (SpiderMonkey 31 (1.8)) 63 ~~70~~

```
// first version
// alert([for(c of x=prompt())[x?c.toUpperCase():c,x=c<'!'][0]].join(''))
// new version, thx @nderscore
[for(c of prompt(o=x=''))o+=x=x<'!'?c.toUpperCase():c],alert(o)
```

# Answer
> 2 votes
# R, ~~139~~ 105 bytes

```
for(i in 1:length(p<-strsplit(readline(),"")[[1]])){if(i<2||p[i-1]==" ")p[i]=toupper(p[i])};cat(p,sep="")

```

Ungolfed + explanation:

```
# Assign p to be a vector of the input read from stdin, split into characters

for(i in 1:length(p <- strsplit(readline(), "")[[1]])) {

    # If we're at the first iteration or the previous character was a space

    if (i < 2 || p[i-1] == " ") {

        # Convert the current character to its uppercase equivalent

        p[i] <- toupper(p[i])
    }
}

# Join the vector elements into a single string and print it to stdout
cat(p, sep = "")

```

---

# R with regex, ~~49~~ 41 + 30 = 71 bytes

I'm really bummed; this actually has a better score using regular expressions with the penalty.

```
gsub("(^.| +.)","\\U\\1",readline(),pe=T)

```

This matches any single character at the beginning of the string or following any number of spaces and replaces it with an uppercase version of the capture. Note that applying `\\U` is legit and has no effect for non-letters. `pe=T` is interpreted as `perl = TRUE` since it takes advantage of R's partial matching of function parameters and the synonym for `TRUE`. For whatever reason, R doesn't use Perl-style regular expression by default.

Thanks to MickyT for helping save 8 bytes on the regex approach!

# Answer
> 2 votes
# C, 125

Not the shortest of solutions, but I really like to golf in C.

```
char b[99];main(c){while(scanf("%[A-Za-z_-]",b)==1)islower(*b)&&(*b&=223),printf("%s",b);~(c=getchar())&&putchar(c)&&main();}

```

ungolfed:

```
char b[99];
main(c)
{
  while(scanf("%[A-Za-z_-]", b) == 1) {
    if(islower(b[0])) {
      b[0] &= 0xDF;
    }
    printf("%s", b);
  }
  if((c = getchar()) != -1) {
      putchar(c);
      main();
  }
}

```

I don't know wheter using regex-like syntax in `scanf` is streching the rules, but it works quite nicely. (Well, technically it's not a *full* regex)

An other thing to consider is that this code only works for words shorter than 99 bytes. But I think this solution will work for most cases.

# Answer
> 2 votes
**Haskell: 127 characters**

```
import Data.List
import Data.Char
i=isSpace
s a b=i a==i b
u (w:ws)=(toUpper w):ws
f w=concatMap u$groupBy s w
main=interact f

```

# Answer
> 2 votes
# PHP, 82

```
echo join(' ',array_map(function($s){return ucfirst($s);},explode(' ',$argv[1])));

```

Usage :

```
$ php code.php "eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye"

```

# Answer
> 2 votes
# Java, 201 178 174 bytes

```
class C{public static void main(String[]a){for(String s:a[0].split(" ")){int c=s.length()>0?s.charAt(0):0;System.out.print((c>96&c<123?(char)(c-32)+s.substring(1):s)+" ");}}}

```

I'm back after realizing that my previous program did not preserve spaces.

First time I've had to submit an entire class before. Pass in the string as a command-line argument wrapped in quotes. (I never thought I could get it this short!)

# Answer
> 2 votes
# Python 2, ~~64~~ ~~59~~ 63

**Try it here**

This iterates through each word, converting the first character of each to uppercase, then printing it with a space after. I have to check if the split substring is not empty, which refers to multiple spaces in a row.

```
for w in raw_input().split(" "):print w and w[0].upper()+w[1:],

```

# Answer
> 2 votes
# Mathematica, 66 bytes

```
Print@StringReplace[InputString[],WordBoundary~~a_:>ToUpperCase@a]

```

I would use `ToCamelCase`, but it doesn't preserve spacing.

# Answer
> 2 votes
# R, ~~96~~ 93

A different approach than Alex A's. I'm not using a loop, rather creating a another vector with a space prepended, then uppercasing any character in the original vector that is sitting under a space.

```
p=(strsplit(readline(),''))[[1]];s=c(' ',p);p[e]=toupper(p[e<-s==' ']);cat(head(p,-1),sep='')

```

Doesn't beat the regexp version though.

**Edit** I love it when you learn something new. Replace `p[-length(p)]` with `head(p,-1)`

# Answer
> 2 votes
**Python 3, 58 63 59 chars**

```
print(*(c and c[0].upper()+c[1:] for c in input().split(" ")))

```

I have to add 5 characters because of bugfix

# Answer
> 2 votes
# Python 3, 101 bytes

```
x=list(' '+input())
for i in range(len(x)-1):
 if x[i-1]==' ':x[i]=x[i].title()
print(''.join(x[1:]))

```

# Answer
> 2 votes
# , 5 (non-competing)

```
$òBvU

```

Try it online!

Not too interesting. Just a direct port of my vim answer:

```
$        #Move to the last character
 ò       #Recursively
  B      #Move back a WORD
   vU    #Capitalize

```

# Answer
> 2 votes
# Brachylog, 12 bytes

```
ṇ₁{ụʰ|}ᵐ~ṇ₁w

```

Try it online!

```
           w    Print
                the input
ṇ₁              split on spaces
  {   }ᵐ        with every word
    ʰ           having its first letter
   ụ            uppercased
     |          (without failing on empty words)
        ~ṇ₁     and then joined by spaces.

```

If this was allowed to be a function which would normalize runs of spaces to just one space, it would only be two bytes shorter: `ṇ₁{ụʰ}ˢ~ṇ₁`. That would be another two bytes shorter if we'd figured out how to parse chained metapredicates (`ṇ₁ụʰˢ~ṇ₁`), but since handling runs of spaces requires the `|`, it doesn't actually matter for this challenge.

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
#εćuì}ðý

```

Try it online.

**Explanation:**"

```
#         # Split the (implicit) input-string by the space character
          # (multiple adjacent spaces will give empty items in the list)
 ε        # Map each string to:
  ć       #  Extract the head; pop and push the remainder and head separately to the stack
   u      #  Uppercase the head
    ì     #  Prepend it in front of the remainder again
     }ðý  # After the map: join by spaces (which is output implicitly as result)

```

# Answer
> 2 votes
# Python 3, 59 bytes

```
print(*(w[0].upper()+w[1:]for w in input().split(' ')if w))

```

Try it online!

# Answer
> 2 votes
# Vyxal `s`, 7 bytes

```
ðẆƛḣ$⇧p

```

Try it Online!

Fixed thanks to lyxal.

```
ðẆƛ     # Over each word...
   ḣ$ p # To the first character...
     ⇧  # Uppercase it

```

# Answer
> 2 votes
# Lexurgy, 116 bytes

Simple replacement of lowercase letters at the beginning of a word to uppercase.

This works because of how Lexurgy handles whitespace in the input. The `$` symbol denotes a word boundary, which is defined as any sort of whitespace before or after any character. As a result, input like `hello world` on a single line is considered as 2 words rather than 1 word.

```
a:
{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}=>{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z}/$ _

```

# Answer
> 2 votes
# Japt `-S`, 7 bytes

```
¸®©hZÎu

```

Try it

```
¸®©hZÎu     :Implicit input of string
¸           :Split on spaces
 ®          :Map each Z
  ©         :  Logical AND with
   h        :  Replace first character with
    ZÎ      :    First character of Z
      u     :    Uppercased
            :Implicit output joined with spaces

```

# Answer
> 2 votes
## C - 85 Bytes

```
s[99]={32};j;main(i){for(;read(0,&j,1);)putchar(s[i++]=j<97|j>122|s[i-1]-32?j:j-32);}

```

Thanks to @ceilingcat because I saved 43 bytes with his modification.

**Ungolfed**

```
s[99] = {32};
j;

main(i)
{
   for( ; read(0, &j, 1); )

   putchar(s[i++] = j < 97 | j > 122 | s[i - 1] - 32 ?j :j - 32);
}

```

**Explanation**

A simple program that reads characters from the console and capitalizes each "valid" word and then displays it on the console as well. It was tested in GCC and it generates some warnings.

# Answer
> 1 votes
# Ruby: 46 characters

```
l=0
gets.chars{|c|l&&c.upcase!
l=c==" "
$><<c}

```

Sample run:

```
bash-4.3$ ruby -e 'l=0;gets.chars{|c|l&&c.upcase!;l=c==" ";$><<c}' <<< 'eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye'
ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye

```

# Answer
> 1 votes
# GNU sed, 20 + 1 (-r flag) +30 (regex penalty) = 51

```
s/(^| +)(.)/\1\u\2/g

```

(thks @manatwork for helping me save 4 bytes)

Usage :

```
sed 's/\(^\| \)\(.\)/\1\u\2/g' <<< "eCommerce and eBusiness are cool, don't you agree, Richard III?"

```

# Answer
> 1 votes
# PHP, 91+30 bytes

Well, all the ideas were used.

I had to resort to drastic measures and build a huge piece of code:

```
<?=preg_replace_callback('@( |^)([a-z])@',function($a){return$a[1].($a[2]^' ');},$_GET[s]);

```

The only function it uses is to fetch the small letters, using regex.

# Answer
> 1 votes
# C#, ~~143~~ ~~138~~123 bytes

```
class G{static void Main(string[]a){var l=' ';foreach(var c in a[0]){System.Console.Write(l==' '?char.ToUpper(c):c);l=c;}}}

```

Runs as a command line util. Will try and golf it down from here. Comments & critique encouraged!

# Answer
> 1 votes
# Ruby(55)

```
gets.chars.inject(' '){|c,d|print c<?!?d.upcase():d;d}

```

I know that a better ruby solution exits in an old answer, but I like this better.

note:`c<?!` checks for chars that come before `!`, which are just control/whitespace.

# Answer
> 1 votes
# Rebol - ~~56~~ 51

```
print map-each n split input" "[uppercase/part n 1]

```

The above works correctly with the test case and also with multiple whitespace input.

An interesting (but longer!) alternative version would to use the `parse dialect` (not a regex!) which when golfed would come down to 65 chars:

```
parse s: input [any [x: thru [" " | end] (uppercase/part x 1)]] print s

```

# Answer
> 1 votes
# Java, 142

First post here as well, but found that the requirements are a one to one mapping to the way Java handles arguments.

```
class X{public static void main(String[]s){for(String p:s){System.out.append(p.toUpperCase().charAt(0)).append(p,1,p.length()).append(' ');}}}

```

Unfortunately, because they are command line arguments, spaces are not preserved, and the offending words (`don't`) have to be quoted (`"don't"`). So while I didn't entirely meet all the criteria I just wanted to share a Java solution that's under 200 bytes.

# Answer
> 1 votes
# Groovy - 69

```
t=args[0];t.eachWithIndex{c,i->print!i|t[i-1]==' '?c.toUpperCase():c}

```

# Answer
> 1 votes
# KDB(Q), 30 bytes

```
{@[x;0,1+where" "=-1_x;upper]}

```

# Explanation

```
                  -1_x            / handle case where last char is space
       1+where" "=                / find index of space and shift by 1
     0,                           / include the first char
 @[x;                 ;upper]     / apply upper case
{                            }    / lambda

```

# Test

```
q){@[x;0,1+where" "=-1_x;upper]}t
"ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye"

```

# Answer
> 1 votes
# Jelly, 9 bytes

```
ṣ⁶Œu1¦€j⁶

```

Try it online!

### How it works

```
ṣ⁶Œu1¦€j⁶  Main link. Argument: s (string)

ṣ⁶         Split s at spaces.
      €    Each; map this over the chunks:
    1¦       Apply this to the first character:
  Œu           Uppercase.
       j⁶  Join, separating by spaces.

```

# Answer
> 1 votes
# s-lang, 8 bytes + 30 = 38

```
c![[^ ]*

```

s-lang

Procedure:

* Capitalize the first letter of every range matched by the regex.
    + Any number of Every character not in Space.

# Answer
> 1 votes
## VTL-2, 89 bytes

```
1 B=A
2 A=$
3 A=A-(32*(((B=0)+(B=32))*(A>97)*(A<123
4 $=8*(1-(A=4
5 $=B
6 #=1-(A=4

```

If I read the challenge right, input seems fairly flexible, so... This operates every time a character is input. Input is terminated by an EOT (`Ctrl``D`). Output is one character behind, so every time you input a character, the previous one will be output. This really confused my brain when I was entering the test case.

Line 1 is fairly obvious, it copies the value of `B` into `A`. It's fine to start the program from here because uninitialized variables are assumed to be 0. Line 2 takes a single character input from the terminal and assigns `A` to its ASCII value. Fairly straightforward so far. Line 3 is a bit of a doozy, but it translates to (keeping in mind that `B` is the previous character entered, and `A` is the character just entered) `IF (B==NULL OR B==" ") AND (96 < A < 123) THEN A=A-32`. Because `$` echoes, line 4 inserts a backspace character so long as `A` isn't EOT. Line 5 prints `B`, and line 6 is akin to `IF A!=EOT THEN GOTO 1`.

# Answer
> 1 votes
# JavaScript, 59 bytes

```
n=>n.split` `.map(e=>e[0].toUpperCase()+e.slice(1)).join` `

```

As I mentioned in some of my other answers, my solutions tend to be extremely boring and unimaginative.

# Answer
> 1 votes
# Factor, 57 bytes

```
readln >words [ unclip ch>upper prefix ] map ""join write

```

Try it online!

Factor has a `capitalize` word, but for some reason it lowercases the rest of the word, so I couldn't use it.

# Answer
> 1 votes
# Ly, 33 bytes

```
irs[:'`Gf'zG!fpl**[p' -0]p' =spo]

```

Try it online!

Pretty much a straight-forward application of the rules this time...

```
irs                               - read input, reverse, stash non-zero "capitalize?" state
   [                            ] - for each codepoint in the input...
    :                             - duplicate current char
     '`G                          - is it >="a"?
        f                         - pull current char forward
         'zG!                     - is it <="z"?
             fp                   - pull current char forward, delete it
               l                  - load "capitalize?" flag
                **                - multiply all three tests values
                  [p   0]p        - if/then, true if we need to capitalize
                    ' -           - sub 32 from codepoint to capitalize
                          ' =     - is the current char a space?
                             s    - save result as "capitalize?" flag
                              p   - delete test result
                               o  - print current codepoint as a char

```

# Answer
> 0 votes
# Java, 167 bytes

```
public class G{public static void main(String[]e){for(String n:e[0].split(" ")){System.out.print(n.length()<1?"":n.substring(0,1).toUpperCase()+n.substring(1)+" ");}}}

```

Ungolfed:

```
public class G {
    public static void main(String[] e) {
        for (String n: e[0].split(" ")) {
            System.out.print(n.length() < 1 ? "" : n.substring(0, 1).toUpperCase() + n.substring(1) + " ");
        }
    }
}

```

# Answer
> 0 votes
## JavaScript, (ES6 RegEx Replacer) 66 bytes

```
alert(prompt().replace(/(^[A-Z])|(\s[A-Z])/gi,m=>m.toUpperCase()))
```

# Answer
> 0 votes
# Perl 6, 35 bytes

```
say slurp.split(" ")>>.tc.join(" ")

```

Try it online!

# Answer
> 0 votes
# C89 (clang), ~~60~~ 58 bytes

* -2 bytes thanks to @ceilingcat

```
c;main(a){read(0,&c,1)&&main(putchar(a?toupper(c):c)<33);}

```

This treats non-printable ASCII as spaces (including newlines and tabs), it could be fixed for +1 byte:

```
c;main(a){read(0,&c,1)&&main(putchar(a?toupper(c):c)==32);}

```

Try it online!

# Answer
> 0 votes
# Thunno 2 , 5 bytes

```
OıḢRƤ

```

Attempt This Online!

#### Explanation

```
OıḢRƤ  # Implicit input
O      # Split by spaces
 ı     # Map over this list:
  Ḣ    #  Head extract
   R   #  Uppercase
    Ƥ  #  Prepend
       # Implicit output, joined by spaces

```

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


title: Are all three integers distinct?

text:
# Question
Title: Are all three integers distinct?
You will be given 3 integers as input. The inputs may or may not be different from each other. You have to output 1 if all three inputs are different from each other, and 0 if any input is repeated more than once.

This is , so make your code as short as possible!

# Answer
# Python 3, ~~23~~ ~~21~~ 20 bytes

```
lambda*a:len({*a})>2

```

Try it online!
> 10 votes

# Answer
# Perl 6, 7 bytes

```
*.Set>2

```

Try it online!
> 8 votes

# Answer
# , 13 bytes

A different solution to @Kirill by using `mad()` for an unintended purpose!

```
mad(scan())>0

```

Try it online!
> 8 votes

# Answer
# JavaScript, 22 bytes

If we can output boolean values then the last 2 bytes can be removed.

```
a=>new Set(a).size>2&1

```

Try it online

For the same byte count, this works on arrays of any size but assumes the input will never contain a `0` and output is a boolean.

```
a=>!a[new Set(a).size]

```

Try it online
> 5 votes

# Answer
# , ~~24~~ ~~22~~ 20 bytes

```
all(table(scan())<2)

```

Try it online!

Returns a boolean, but as folks have already discussed on the Python answer, this should be OK.

Thanks to digEmAll for saving 2 bytes.
> 5 votes

# Answer
# Ruby, 16 bytes

```
->a{1-(a<=>a|a)}

```

Try it online!
> 4 votes

# Answer
# Cubix, ~~55~~ 25 bytes

*-29 thanks to Jo King*

```
O@O1u|@O@II-!/;I-!/;u^?-p

```

Try it online!

It should be possible to golf off quite a few bytes.
> 4 votes

# Answer
# 05AB1E, 2 bytes

```
ÙQ

```

Try it online or verify some more cases.

**Explanation:**

```
Ù     # Uniquify the (implicit) input
 Q    # Check if it's still equal to the (implicit) input

```
> 3 votes

# Answer
# Mathematica, 13 bytes

```
Boole[E!=##]&

```

Pure function. Takes three integers as input and returns `0` or `1` as output. I know that this is rather similar to David G. Stork's answer, but it exploits `SlotSequence` to shave off a byte (as compared to `Boole@*Unequal`).
> 3 votes

# Answer
# , 4 bytes

```
-:~.

```

Try it online!

## Explanation:

Is the argument equal `-:` to itself after removing the duplicates `~.`
> 3 votes

# Answer
# K (oK), 4 bytes

```
3=#?

```

Try it online!

Does the count of the distinct elements equal 3?
> 3 votes

# Answer
# Japt `-N`, 3 bytes

```
eUâ

```

Try it

---

## Explanation

deduplicates the input and `e` tests if it's equal to the original.
> 2 votes

# Answer
# C (gcc), ~~25~~ 26 bytes

```
f(a,b,c){a=a-b&&a-c&&b-c;}

```

Try it online!
> 2 votes

# Answer
# Powershell, ~~27~~ 25 bytes

*-2 bytes thanks @AdmBorkBork*

```
+!(($args|group).Count-3)

```

Test script:

```
$f = {
+!(($args|group).Count-3)
}

&$f 1 2 3
&$f 3 2 1
&$f 2 1 3
&$f 2 2 3
&$f 2 1 1
&$f 2 1 2

```

Explanation:

```
    $args|group           # Group arguments
   (           ).Count    # Count of groups
  (                   -3) # is 0 if inputed integers are unique
 !                        # operator not converts int to boolean: true if integers are unique
+                         # converts boolean to int: 1 if integers are unique, otherwise 0

```
> 2 votes

# Answer
# brainfuck, 91 bytes

```
,>,>,[-<-<->>]>>+++++++[>+++++++<-]+<<<<[>]>>[<<<[-<->]<[>]>>->[>.<<<->>-]<+]<+[>>>[>]<-.>]

```

Try it online!

### How it works

```
,>,>,                   'read input as A, B, and C
[-<-<->>]>>+            'compute A-C, B-C
++++++[>+++++++<-]+     'prepare output
<<<<[>]>>               'if A-C != 0 && B-C != 0
[
    <<<[-<->]           'compute A-B
    <[>]>>->            'if A-B != 0
    [>.<<<->>-]         'print 1
    <+
]
<+
[                       'else (this else is for both of the if statements, even though they are nested... wierd, I know)
    >>>[>]
    <-.>                'print 0
]

```
> 2 votes

# Answer
# Jelly, 2 bytes

Try it online!
> 2 votes

# Answer
# Common Lisp, ~~25~~ 2 bytes

```
/=

```

Try it online!

-23 bytes thanks to @ceilingcat!
> 2 votes

# Answer
# APL (Dyalog Unicode), 3 bytesSBCS

Anonymous tacit prefix function. Takes list as argument.

```
∪≡⊢

```

Try it online!

does the set of unique elements from the argument

match

the unmodified argument?
> 1 votes

# Answer
# Clean, 32 bytes

```
import Data.List
$l|hasDup l=0=1

```

Try it online!
> 1 votes

# Answer
# Java 9, ~~43~~ 27 bytes

*thanks to @Olivier Grégoire*

```
(a,b,c)->a!=b&b!=c&a!=c?1:0

```

Previous attempt:

```
(a)->a[0]==a[1]||a[0]==a[2]||a[1]==a[2]?0:1

```
> 1 votes

# Answer
# Attache, 10 bytes

```
`==#Unique

```

Try it online!

This is a fork of the operator ``==` and `Unique`, equivalent to:

```
{ _ == Unique[_] }

```

## Alternatives

`{#_=#Unique[_]}` (15 bytes)

`Any##Same=>Pairs@Sort` (21 bytes)

`Any@{`=&>_[[0'1,1'2,2'0]]}` (26 bytes)

`&${not(x=y or y=z or x=z)}` (26 bytes)

`&${x/=y and y/=z and x/=z}` (26 bytes)

`{Any!Same=>Chop&2!_[0'1'1'2'2'0]}` (33 bytes)
> 1 votes

# Answer
# \>\<\>, ~~19~~ 17 bytes

-2 bytes by Jo King.

```
:{:{:{=}=}=++0=n;

```

Try it online!
> 1 votes

# Answer
# Red, 21 bytes

```
func[b][b = unique b]

```

Try it online!
> 1 votes

# Answer
# T-SQL, 39 bytes

```
SELECT IIF(a=b OR b=c OR c=a,0,1)FROM s

```

Input is taken as separate columns **a, b, c** from a pre-existing table **s**, per our IO standards.

Tried a variation using `COUNT DISTINCT` from input taken as separate rows, but that was a couple bytes longer.
> 1 votes

# Answer
# Jelly, ~~5~~ 6 bytes

```
ɠḲQL=3

```

Try it online!

From 5 to 6 bytes because this is my first time and I messed up (whoops) fixed it now

```
ɠḲQL=3
^^^^^
||||Is it equal to three?
|||How many unique numbers do we have? (length of unique numbers array)
||Sort By Unique
|Split by Spaces
Read Input

```
> 1 votes

# Answer
# Pyth, 3 bytes

```
s{I

```

Takes input as a list.
Try it here

### Explanation

```
s{I
 {IQ     Check if the (implicit) input is invariant under deduplication.
s        Cast to int.

```

If we're allowed to treat True and False as 1 and 0 (which they are under the hood in Pyth), we can drop the `s` to get down to 2 bytes.
> 1 votes

# Answer
# SmileBASIC, ~~25~~ 24 bytes

```
READ A,B,C?A-B&&B-C&&C-A

```
> 1 votes

# Answer
# Ruby, 11 bytes

```
->a{a==a|a}

```

Try it online!

Assuming we can return a boolean. Which everyone is doing nowadays.
> 1 votes

# Answer
# Brachylog, 6 bytes

```
d?∧1|0

```

Try it online!

# short explanation

`d?` **d**eduplcates input an test if still equal to input(**?**)

`∧1` if true return 1

`|0` else return 0
> 1 votes

# Answer
# JavaScript (Node.js), 67 bytes

```
f=a=>a.map((m,i)=>a.map((n,j)=>m==n&i!=j).every(z=>!z)).every(y=>y)

```

Try it online!
> 1 votes

# Answer
# 14 bytes

```
{x~distinct x}

```

Technically this solution will return '1b' or '0b', which is the way a boolean value is distinguished from a numeric type, though it retains all arithmetic functionality, and so is in essence a 1 or 0:

```
q)1b +35
36

```

To return 1 or 0 non-boolean you have the below, which takes the byte count to 21

```
{$[x~distinct x;1;0]}

```
> 1 votes

# Answer
# PHP, 38 bytes

```
echo(4==count(array_unique($argv)))*1;

```

Called with e.g. `php codegolf.php 2 3 4`. $argv always contains the filename of the script, hence 3 unique numbers make 4 elements.
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Easy peasy
> 1 votes

# Answer
# Julia 1.0, ~~18~~ 11 bytes

```
~x=x==x∪x

```

Try it online!

-7 bytes (!!) thanks to MarcMush: replace `length(x∪x)>2` with `x==x∪x`
> 1 votes

# Answer
# Triangularity, 17 bytes

```
..i..
.MiC.
}u)3=

```

Try it online!

### How it works

Excluding the mandatory triangular padding, we're left with:

```
iMiC}u)3=

```

Which can minimally be explained as: Push all STDIN as an array of strings (representing each line of input), count the occurrences of all of STDIN's elements in itself (which, in case all are distinct, should yield **\[1, 1, 1\]**), sum, then check whether the sum is equal to **3**. There are 2 tricks here (which together save no less than 14 bytes):

* Using `i` and treating the inputs as strings rather than integers – which is quite uncommon, as `)IE` is frequently used instead, taking input as a list.
* Instead of checking whether they all are equal to **1** and then taking the product – or equivalently, taking the product and checking whether it is equal to **1** – this takes the *sum* and compares it with **3**. Proving the validity of this method is obviously trivial: **\[1, 1, 1\]** is the only valid way to partition **3** into 3 positive integers summing to it and the contents of this list are always positive, as every element of a collection must occur at least once in it :P.
> 0 votes

# Answer
# Charcoal, 14 bytes

```
≔Ｅ³ＮθＩ¬⊖⌈Ｅθ№θι

```

Try it online! Link is to verbose version of code. 5 bytes could be saved by using a slightly non-standard input format `[[x, y, z]]`. Explanation:

```
≔Ｅ³Ｎθ

```

Input 3 numbers and make a list.

```
Ｉ¬⊖⌈Ｅθ№θι

```

Count the number of occurrences of each number in the list. Take the maximum, subtract 1, take the logical not, then cast to string for implicit print.
> 0 votes

# Answer
# PHP, 30 bytes

```
<?=array_unique($argv)==$argv;

```

takes input from command line arguments; prints `1` for truthy, empty string for falsy
> 0 votes

# Answer
# Flobnar, 25 bytes

```
$-<*\\\!!@
::*<&&&
-$$>
$

```

Try it online!

Given integers `a,b,c`, evaluates `!!((c-b)*(b-a)*(c-a))`
> 0 votes

# Answer
# C (gcc), 50 41 bytes

**-9 bytes thanks to GB !**

```
m(int*a){a=*a==a[2]^*a==*++a^*a==*++a^1;}

```

Try it online!

No built-in sets in C, and iterating is too long, but at least i can shave off a few bytes by taking advantage of the fact that `*a == a[0]` ...
> 0 votes

# Answer
**SWIFT** **37 Bytes**

```
Set(Array(readLine()!)).count==3 ?1:0

```
> 0 votes

# Answer
# Julia 1.0, 24 bytes

```
f(x...)=length(Set(x))>2

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 12 bytes

```
a->#Set(a)>2

```

Try it online!
> 0 votes

# Answer
# Stax, 3 bytes

```
ä▼Z

```

Run and debug it

**Explanation**

```
ux=         #Full program, unpacked, implicit input as array
u           #Keep only unique elements in array, maintaining first order of appearance
 x=         #Copy original input onto stack, is it equal to unique-ified array.

```

Short and sweet. Wish Stax would implicitly check against "X" register if there was nothing to check against, but it works out regardless.
> 0 votes

# Answer
# Haskell, 26 bytes

```
g a b c=and$map(==)[a,b,c]

```
> 0 votes

# Answer
# Math++, ~~40~~ 29 bytes

```
?>a
?>b
?>c
(a-b)&(b-c)&(a-c)

```
> 0 votes

# Answer
# Lua, 38 bytes

```
x,y,z=...print(x~=y and x~=z and y~=z)

```

### Try it online!
> 0 votes

# Answer
# C (clang), 32 bytes

```
f(a,b,c){return a!=b&b!=a&a!=c;}

```

Try it online!
> 0 votes

# Answer
## JavaScript, 25 24 28 27 23 bytes

Using bitwise, comparison and logical operators Try it online!

(*4 bytes saved courtesy of Jonathan Frech*)

```
(a,b,c)=>a!=b&a!=c&b!=c

```
> 0 votes

# Answer
# Pepe, ~~85~~ 77 bytes

```
rEeEREeErrEEEEEeRrEeErrEEEEEerEEEEEEERerEEEEEerRrEEEEEEeErREEREEEEErEeReeReEE

```

Try it online! Input is `a,b,c`. Change the "separated by" box to `,` to make it work!
> 0 votes

# Answer
# Rust, ~~29~~ 23 bytes

```
|a,b,c|a!=b&&b!=c&&a!=c

```

Try it online!
> 0 votes

# Answer
# MathGolf, 2 bytes

```
▀=

```

Try it online!

## Explanation

```
▀    Get unique elements
 =   Check if equal to the input

```
> 0 votes

# Answer
# Braingolf, 5 bytes

```
ul3-n

```

Try it online!

Edit: fixed from identical -\> distinct
> 0 votes

# Answer
# Pyth, 5 bytes

```
s<2l{

```

Try it online!

Looks like someone already did pyth but I didn't know about the I for testing invariants.
> 0 votes

# Answer
# Rust, 17 bytes

Anything XORd with itself yields zero. So. Any language with multiplication and XOR can do this:

```
(a^b)*(b^c)*(a^c)

```

Since input specifics were rather vague I chose a liberal interpretation. Or if you want to be more strict, we can define it as a closure (kind of like a lambda function),

24 bytes

```
|a,b,c|(a^b)*(b^c)*(a^c)

```

Try it on the Rust Playground
> 0 votes

# Answer
# Husk, 3 bytes

```
S=U

```

Try it online! Takes the three numbers in a list.
> 0 votes

# Answer
# Dash, ~~27~~ 24 bytes

```
$(($1-$2&&$2-$3&&$3-$1))

```

Try it online!

Sorry for a boring answer; at first if bashism would work, but I could not get out of POSIXism.

The code above evaluates to a string of either 0 or 1.
> 0 votes

# Answer
# Pxem, Filename: 28 bytes + Content: 0 bytes = 28 bytes.

* Filename: `._._._.e.z.c.c.z1.o.d.a.a0.o`
* Content: enpty.

Try it online! (with pxem.posixism)

## With comments

```
XX.z
# for three times; do push( read integer); done
.a._._._XX.z
# call subroutine
## NOTE. When DOT-e is performed when stack is a,b,c,bottom,
## then subroutine begins with same content of stack
## And when subroutine ends when stack is d,e,f,bottom,
## then previous stack would be d,e,f,a,b,c,bottom
## to continue origimal procedure
## In this program content is empty, so is subroutine
## thus x,y,z,bottom to x,y,z,x,y,z,bottom,
## which duplicates entire stack
.a.eXX.z
# while size < 2 && pop != pop; do
.a.zXX.z
  # dup; dup; while size<2 && pop!=pop; do
  ## this is equal to while stack is empty; do
  .a.c.c.zXX.z
    # push '1'; putc pop; exit
    .a1.o.dXX.z
  # done
  .a.aXX.z
# done
.a.aXX.z
# push '0'; putc pop; (implicity) exit
.a0.oXX.z
.a

```
> 0 votes

# Answer
# Factor, 11 bytes

```
all-unique?

```

Try it online!
> 0 votes

# Answer
# K (ngn/k), 10 bytes

```
{(#x)=#?x}

```

Try it online!

A little bit more interesting answer in my opinion, but still boring. Takes a list of integers as input.

Explanations:

```
{(#x)=#?x}  Main function. x is input
       ?    Unique (Remove all duplicated elements)
      #     Length
     =      Is it equal to
 (#x)       The length of x itself

```
> 0 votes

# Answer
## Pascal, 91 B

This is a complete `program` conforming to ISO standard 10206 “Extended Pascal” and at 91 bytes certainly more readable than brain\****.

```
program p(input,output);var x,y,z:integer;begin read(x,y,z);write(ord(card([x,y,z])=3))end.

```

The `[x,y,z]` denotes a *set*, thus duplicate values get collapsed. This means, the set literal `[4, 4, 4]` is identical to `[4]`. The `card` function returns the number of distinct elements in the set. Here this will be anything between 1 and 3 inclusive. We test for equality to 3 (`… = 3`) which evaluates to a Boolean expression (denoted by the built-in constants `false` and `true`) and convert this enumeration value into an `integer` using `ord`.
> 0 votes

# Answer
# Pyt, 6 bytes

```
ĐỤ=Ʃ3=

```

Try it online!

```
Đ         implicit input; Đuplicate
 Ụ        get Ụnique items
  =       is equal element-wise?
   Ʃ      Ʃum of list (coerce booleans to ints)
    3=    is equal to 3?; implicit print

```
> 0 votes

# Answer
# Alice, 22 bytes

```
3&/ M \.!-~?-Zn'0+O@

```

Try it online!

```
3&/ M \                   Reads the three arguments and puts them on the stack
       .!-~?-             Compares the two last arguments, then the first with the last
                          It leaves [0, 0] on the stack if the two numbers are the same
                          Otherwise any other pair of numbers
             Z            Packs the two numbers together [0, 0] yields 0
              n           Logical not, if the pack result is 0 return 1 and any other number returns 0
               '0+O@      Output and bye

```
> 0 votes

# Answer
# Piet \+ ascii-piet, 37 bytes (24×2=48 codels)

```
TAbTlTiTrTtTLDqMmMEuAkAaAqQIBSAMVcRrr

```

Try Piet online!

Probably not the golfiest that could happen but manipulating the stack order in Piet is a bit of a pain.

### Pointer Path
> 0 votes

# Answer
# GolfScript, 4 bytes

```
..|=

```

Try it online!

Input is taken as an array of three numbers

# Explanation

```
..|=
 .|  # Setwise OR the input array with itself
.  = # Is it equal to the initial input?

```
> 0 votes

# Answer
# Thunno 2, 2 bytes

#### Explanation

```
U   # Uniquify the input list
ċ   # Or, take the set union of the input list with itself
ȯ   # Or, take the set intersection of the input list with itself
 ⁼  # Then, check if this new list is equal to the input list

```
> 0 votes

# Answer
**Python 2**

```
def e(a,b,c):return 1 if len(set([a,b,c]))>2 else 0

```

...could be shortened to

```
def e(a,b,c):return len(set([a,b,c]))>2

```
> -1 votes

---
Tags: code-golf, number, decision-problem
---


# Question
Title: Calculate the Hafnian as quickly as possible
The challenge is to write the fastest code possible for computing the Hafnian of a matrix.

The Hafnian of a symmetric `2n`-by-`2n` matrix `A` is defined as:

$$\operatorname{haf}(A)=\frac{1}{n ! 2^n} \sum\_{\sigma \in S\_{2 n}} \prod\_{j=1}^n A\_{\sigma(2 j-1), \sigma(2 j)}$$

Here \\$ S\_{2 n} \\$ represents the set of all permutations of the integers from `1` to `2n`, that is `[1, 2n]`.

The wikipedia link also gives a different looking formula which may be of interest (and even faster methods exist if you look further on the web). The same wiki page talks about adjacency matrices but your code should work for other matrices as well. You can assume the values will all be integers but not that that they are all positive.

There is also a faster algorithm but it seems hard to understand. and Christian Sievers was the first to implement it (in Haskell).

In this question matrices are all square and symmetric with even dimension.

## Reference implementation (note this is using the slowest possible method).

Here is some example python code from Mr. Xcoder.

```
from itertools import permutations
from math import factorial

def hafnian(matrix):
    my_sum = 0
    n = len(matrix) // 2
    for sigma in permutations(range(n*2)):
        prod = 1
        for j in range(n):
            prod *= matrix[sigma[2*j]][sigma[2*j+1]]
        my_sum += prod
    return my_sum / (factorial(n) * 2 ** n)

print(hafnian([[-1, 1, 1, -1, 0, 0, 1, -1], [1, 0, 1, 0, -1, 0, -1, -1], [1, 1, -1, 1, -1, -1, 0, -1], [-1, 0, 1, -1, -1, 1, -1, 0], [0, -1, -1, -1, -1, 0, 0, -1], [0, 0, -1, 1, 0, 0, 1, 1], [1, -1, 0, -1, 0, 1, 1, 0], [-1, -1, -1, 0, -1, 1, 0, 1]]))
4

M = [[1, 1, 0, 0, 0, 0, 0, 1, 0, 0], [1, 1, -1, 0, -1, 1, 1, 1, 0, -1], [0, -1, -1, -1, 0, -1, -1, 0, -1, 1], [0, 0, -1, 1, -1, 1, -1, 0, 1, -1], [0, -1, 0, -1, -1, -1, -1, 1, -1, 1], [0, 1, -1, 1, -1, 1, -1, -1, 1, -1], [0, 1, -1, -1, -1, -1, 1, 0, 0, 0], [1, 1, 0, 0, 1, -1, 0, 1, 1, -1], [0, 0, -1, 1, -1, 1, 0, 1, 1, 1], [0, -1, 1, -1, 1, -1, 0, -1, 1, 1]]

print(hafnian(M))
-13

M = [[-1, 0, -1, -1, 0, -1, 0, 1, -1, 0, 0, 0], [0, 0, 0, 0, 0, -1, 0, 1, -1, -1, -1, -1], [-1, 0, 0, 1, 0, 0, 0, 1, -1, 1, -1, 0], [-1, 0, 1, -1, 1, -1, -1, -1, 0, -1, -1, -1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1, 0], [-1, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, -1, 0, 1, 1, -1, -1, 0, 1, 0], [1, 1, 1, -1, 0, 1, -1, 1, -1, -1, -1, -1], [-1, -1, -1, 0, 0, 1, -1, -1, -1, 1, -1, 0], [0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 1, 1], [0, -1, -1, -1, -1, 1, 1, -1, -1, 1, 0, -1], [0, -1, 0, -1, 0, 0, 0, -1, 0, 1, -1, 1]]

print(hafnian(M))
13

M = [[-1, 1, 0, 1, 0, -1, 0, 0, -1, 1, -1, 1, 0, -1], [1, -1, 1, -1, 1, 1, -1, 0, -1, 1, 1, 0, 0, -1], [0, 1, 1, 1, -1, 1, -1, -1, 0, 0, -1, 0, -1, -1], [1, -1, 1, -1, 1, 0, 1, 1, -1, -1, 0, 0, 1, 1], [0, 1, -1, 1, 0, 1, 0, 1, -1, -1, 1, 1, 0, -1], [-1, 1, 1, 0, 1, 1, -1, 0, 1, -1, -1, -1, 1, -1], [0, -1, -1, 1, 0, -1, -1, -1, 0, 1, -1, 0, 1, -1], [0, 0, -1, 1, 1, 0, -1, 0, 0, -1, 0, 0, 0, 1], [-1, -1, 0, -1, -1, 1, 0, 0, 1, 1, 0, 1, -1, 0], [1, 1, 0, -1, -1, -1, 1, -1, 1, 1, 1, 0, 1, 0], [-1, 1, -1, 0, 1, -1, -1, 0, 0, 1, -1, 0, -1, 0], [1, 0, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, -1, 1, 0, 1, 1, 0, -1, 1, -1, 1, 1, -1], [-1, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, -1, -1]]

print(hafnian(M))
83

```

**The task**

You should write code that, given an `2n` by `2n` matrix, outputs its Hafnian.

As I will need to test your code it would be helpful if you could give a simple way for me to give a matrix as input to your code, for example by reading from standard in. I will test your code in randomly chosen matrices with elements selected from {-1, 0, 1}. The purpose of testing like this is to reduce the chance the Hafnian will be a very large value.

Ideally your code will be able to read in matrices exactly as I have them in the examples in this question straight from standard in. That is the input would look like `[[1,-1],[-1,-1]]` for example. If you want to use another input format, please ask and I will do my best to accommodate.

**Scores and ties**

I will test your code on random matrices of increasing size and stop the first time your code takes more than 1 minute on my computer. The scoring matrices will be consistent for all submissions in order to ensure fairness.

If two people get the same score then the winner is the one which is fastest for that value of `n`. If those are within 1 second of each other then it is the one posted first.

**Languages and libraries**

You can use any available language and libraries you like but no pre-existing function to compute the Hafnian. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.\`

**My Machine** The timings will be run on my 64-bit machine. This is a standard ubuntu install with 8GB RAM, AMD FX-8350 Eight-Core Processor and Radeon HD 4250. This also means I need to be able to run your code.

**Call for answers in more languages**

It would be great to get answers in your favorite super fast programming language. To start things off, how about fortran, nim and rust?

**Leaderboard**

* **52** by miles using **C++**. 30 seconds.
* **50** by ngn using **C**. 50 seconds.
* **46** by Christian Sievers using **Haskell**. 40 seconds.
* **40** by miles using **Python 2 + pypy**. 41 seconds.
* **34** by ngn using **Python 3 + pypy**. 29 seconds.
* **28** by Dennis using **Python 3**. 35 seconds. (Pypy is slower)

# Answer
# Haskell

```
import Control.Parallel.Strategies
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as VB

type Poly = V.Vector Int

type Matrix = VB.Vector ( VB.Vector Poly )

constpoly :: Int -> Int -> Poly
constpoly n c = V.generate (n+1) (\i -> if i==0 then c else 0)

add :: Poly -> Poly -> Poly
add = V.zipWith (+)

shiftmult :: Poly -> Poly -> Poly
shiftmult a b = V.generate (V.length a)
                           (\i -> sum [ a!j * b!(i-1-j) | j<-[0..i-1] ])
  where (!) = V.unsafeIndex

x :: Matrix -> Int -> Int -> Int -> Poly -> Int
x  _    0  _ m p = m * V.last p
x mat n c m p =
  let mat' = VB.generate (2*n-2) $ \i ->
             VB.generate i       $ \j ->
                 shiftmult (mat!(2*n-1)!i) (mat!(2*n-2)!j) `add`
                 shiftmult (mat!(2*n-1)!j) (mat!(2*n-2)!i) `add`
                 (mat!i!j)
      p' = p `add` shiftmult (mat!(2*n-1)!(2*n-2)) p
      (!) = VB.unsafeIndex
      r = if c>0 then parTuple2 rseq rseq else r0
      (a,b) = (x mat (n-1) (c-1) m p, x mat' (n-1) (c-1) (-m) p')
              `using` r
  in a+b

haf :: [[Int]] -> Int
haf m = let n=length m `div` 2
        in x (VB.fromList $ map (VB.fromList . map (constpoly n)) m)
             n  5  ((-1)^n)  (constpoly n 1)

main = getContents >>= print . haf . read

```

This implements a variation of Algorithm 2 of Andreas Björklund: Counting Perfect Matchings as Fast as Ryser.

Compile using `ghc` with compile time options `-O3 -threaded` and use run time options `+RTS -N` for parallelization. Takes input from stdin.
> 14 votes

# Answer
# Python 3

```
from functools import lru_cache

@lru_cache(maxsize = None)
def haf(matrix):
	n = len(matrix)
	if n == 2: return matrix[0][1]
	h = 0
	for j in range(1, n):
		if matrix[0][j] == 0: continue
		copy = list(matrix)
		del copy[:j+1:j]
		copy = list(zip(*copy))
		del copy[:j+1:j]
		h += matrix[0][j] * haf(tuple(copy))
	return h

print(haf(tuple(map(tuple, eval(open(0).read())))))

```

Try it online!
> 6 votes

# Answer
# C++ (gcc)

```
#define T(x) ((x)*((x)-1)/2)
#define S 1
#define J (1<<S)
#define TYPE int

#include <iostream>
#include <vector>
#include <string>
#include <pthread.h>

using namespace std;

struct H {
    int s, w, t;
    TYPE *b, *g;
};

void *solve(void *a);
void hafnian(TYPE *b, int s, TYPE *g, int w, int t);

int n, m, ti = 0;
TYPE r[J] = {0};
pthread_t pool[J];

int main(void) {
    vector<int> a;
    string s;
    getline(cin, s);

    for (int i = 0; i < s.size(); i++)
        if (s[i] == '0' || s[i] == '1')
            a.push_back((s[i-1] == '-' ? -1 : 1)*(s[i] - '0'));

    for (n = 1; 4*n*n < a.size(); n++);
    m = n+1;

    TYPE z[T(2*n)*m] = {0}, g[m] = {0};

    for (int j = 1; j < 2*n; j++)
        for (int k = 0; k < j; k++)
            z[(T(j)+k)*m] = a[j*2*n+k];
    g[0] = 1;

    hafnian(z, 2*n, g, 1, -1);

    TYPE h = 0;
    for (int t = 0; t < ti; t++) {
        pthread_join(pool[t], NULL);
        h += r[t];
    }

    cout << h << endl;

    return 0;
}

void *solve(void *a) {
    H *p = reinterpret_cast<H*>(a);
    hafnian(p->b, p->s, p->g, p->w, p->t);
    delete[] p->b;
    delete[] p->g;
    delete p;
    return NULL;
}

void hafnian(TYPE *b, int s, TYPE *g, int w, int t) {
    if (t == -1 && (n < S || s/2 == n-S)) {
        H *p = new H;
        TYPE *c = new TYPE[T(s)*m], *e = new TYPE[m];
        copy(b, b+T(s)*m, c);
        copy(g, g+m, e);
        p->b = c;
        p->s = s;
        p->g = e;
        p->w = w;
        p->t = ti;
        pthread_create(pool+ti, NULL, solve, p);
        ti++;
    }
    else if (s > 0) {
        TYPE c[T(s-2)*m], e[m];
        copy(b, b+T(s-2)*m, c);
        hafnian(c, s-2, g, -w, t);
        copy(g, g+m, e);

        for (int u = 0; u < n; u++) {
            TYPE *d = e+u+1,
                  p = g[u], *x = b+(T(s)-1)*m;
            for (int v = 0; v < n-u; v++)
                d[v] += p*x[v];
        }

        for (int j = 1; j < s-2; j++)
            for (int k = 0; k < j; k++)
                for (int u = 0; u < n; u++) {
                    TYPE *d = c+(T(j)+k)*m+u+1,
                          p = b[(T(s-2)+j)*m+u], *x = b+(T(s-1)+k)*m,
                          q = b[(T(s-2)+k)*m+u], *y = b+(T(s-1)+j)*m;
                    for (int v = 0; v < n-u; v++)
                        d[v] += p*x[v] + q*y[v];
                }

        hafnian(c, s-2, e, w, t);
    }
    else
        r[t] += w*g[n];
}

```

Try it online! (13s for n = 24)

Based on the faster Python implementation in my other post. Edit the second line to `#define S 3` on your 8-core machine and compile with `g++ -pthread -march=native -O2 -ftree-vectorize`.

The splits the work in half, so the value of `S` should be `log2(#threads)`. The types can easily be changed between `int`, `long`, `float`, and `double` by modifying the value of `#define TYPE`.
> 6 votes

# Answer
# C

Another impl of Andreas Björklund's paper, which is much easier to understand if you also look at Christian Sievers's Haskell code. For the first few levels of the recursion, it distributes round-robin threads over available CPUs. The last level of the recursion, which accounts for half of the invocations, is optimised by hand.

Compile with: `gcc -O3 -pthread -march=native`; thanks @Dennis for a 2x speed-up

n=24 in 24s on TIO

```
#define _GNU_SOURCE
#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
#include<unistd.h>
#include<pthread.h>
#define W while
#define R return
#define S static
#define U (1<<31)
#define T(i)((i)*((i)-1)/2)
typedef int I;typedef long L;typedef char C;typedef void V;
I n,ncpu,icpu;
S V f(I*x,I*y,I*z){I i=n,*z1=z+n;W(i){I s=0,*x2=x,*y2=y+--i;W(y2>=y)s+=*x2++**y2--;*z1--+=s;}}
typedef struct{I m;V*a;V*p;pthread_barrier_t*bar;I r;}A;S V*(h1)(V*);
I h(I m,I a[][n+1],I*p){
 m-=2;I i,j,k=0,u=T(m),v=u+m,b[u][n+1],q[n+1];
 if(!m){I*x=a[v+m],*y=p+n-1,s=0;W(y>=p)s-=*x++**y--;R s;}
 memcpy(b,a,sizeof(b));memcpy(q,p,sizeof(q));f(a[v+m],p,q);
 for(i=1;i<m;i++)for(j=0;j<i;j++){f(a[u+i],a[v+j],b[k]);f(a[u+j],a[v+i],b[k]);k++;}
 if(2*n-m>8)R h(m,a,p)-h(m,b,q);
 pthread_barrier_t bar;pthread_barrier_init(&bar,0,2);pthread_t th;
 cpu_set_t cpus;CPU_ZERO(&cpus);CPU_SET(icpu++%ncpu,&cpus);
 pthread_attr_t attr;pthread_attr_init(&attr);
 pthread_attr_setaffinity_np(&attr,sizeof(cpu_set_t),&cpus);
 A arg={m,a,p,&bar};pthread_create(&th,&attr,h1,&arg);
 I r=h(m,b,q);pthread_barrier_wait(&bar);pthread_join(th,0);pthread_barrier_destroy(&bar);
 R arg.r-r;
}
S V*h1(V*x0){A*x=(A*)x0;x->r=h(x->m,x->a,x->p);pthread_barrier_wait(x->bar);R 0;}
I main(){
 ncpu=sysconf(_SC_NPROCESSORS_ONLN);
 S C s[200000];I i=0,j=0,k,l=0;W((k=read(0,s+l,sizeof(s)-l))>0)l+=k;
 n=1;W(s[i]!=']')n+=s[i++]==',';n/=2;
 I a[T(2*n)][n+1];memset(a,0,sizeof(a));k=0;
 for(i=0;i<2*n;i++)for(j=0;j<2*n;j++){
  W(s[k]!='-'&&(s[k]<'0'||s[k]>'9'))k++;
  I v=0,m=s[k]=='-';k+=m;W(k<l&&('0'<=s[k]&&s[k]<='9'))v=10*v+s[k++]-'0';
  if(i>j)*a[T(i)+j]=v*(1-2*m);
 }
 I p[n+1];memset(p,0,sizeof(p));*p=1;
 printf("%d\n",(1-2*(n&1))*h(2*n,a,p));
 R 0;
}

```

Algorithm:

The matrix, which is symmetric, is stored in lower-left triangular form. Triangle indices `i,j` correspond to linear index `T(max(i,j))+min(i,j)` where `T` is a macro for `i*(i-1)/2`. Matrix elements are polynomials of degree `n`. A polynomial is represented as an array of coefficients ordered from the constant term (`p[0]`) to xn's coefficient (`p[n]`). The initial -1,0,1 matrix values are first converted to const polynomials.

We perform a recursive step with two arguments: the half-matrix (i.e. triangle) `a` of polynomials and a separate polynomial `p` (referred to as beta in the paper). We reduce the size-`m` problem (initially `m=2*n`) recursively to two problems of size `m-2` and return the difference of their hafnians. One of them is to use the same `a` without its last two rows, and the very same `p`. Another is to use the triangle `b[i][j] = a[i][j] + shmul(a[m-1][i],a[m-2][j]) + shmul(a[m-1][j],a[m-2][i])` (where `shmul` is the shift-multiply operation on polynomials - it's like polynomial product as usual, additionally multiplied by the variable "x"; powers higher than x^n are ignored), and the separate polynomial `q = p + shmul(p,a[m-1][m-2])`. When recursion hits a size-0 `a`, we return the major coefficient of p: `p[n]`.

The shift-and-multiply operation is implemented in function `f(x,y,z)`. It modifies `z` in-place. Loosely speaking, it does `z += shmul(x,y)`. This seems to be the most performance-critical part.

After the recursion has finished, we need to fix the sign of the result by multiplying by (-1)n.
> 4 votes

# Answer
# Python 3

This computes haf(A) as a memoised sum(A\[i\]\[j\] * haf(A without rows and cols i and j)).

```
#!/usr/bin/env python3
import json,sys
a=json.loads(sys.stdin.read())
n=len(a)//2
b={0:1}
def haf(x):
 if x not in b:
  i=0
  while not x&(1<<i):i+=1
  x1=x&~(1<<i)
  b[x]=sum(a[i][j]*haf(x1&~(1<<j))for j in range(2*n)if x1&(1<<j)and a[i][j])
 return b[x]
print(haf((1<<2*n)-1))

```
> 4 votes

# Answer
# Python

This is pretty much a straight-forward, reference implementation of Algorithm 2 from the mentioned paper. The only changes were to only keep the current value of *B*, dropping the values of *β* by only updating *g* when *i**X*, and truncated polynomial multiplication by only calculating the values up to degree *n*.

```
from itertools import chain,combinations

def powerset(s):
    return chain.from_iterable(combinations(s, k) for k in range(len(s)+1))

def padd(a, b):
    return [a[i]+b[i] for i in range(len(a))]

def pmul(a, b):
    n = len(a)
    c = [0]*n
    for i in range(n):
        for j in range(n):
            if i+j < n:
                c[i+j] += a[i]*b[j]
    return c

def hafnian(m):
    n = len(m) / 2
    z = [[[c]+[0]*n for c in r] for r in m]
    h = 0
    for x in powerset(range(1, n+1)):
        b = z
        g = [1] + [0]*n
        for i in range(1, n+1):
            if i in x:
                g = pmul(g, [1] + b[0][1][:n])
                b = [[padd(b[j+2][k+2], [0] + padd(pmul(b[0][j+2], b[1][k+2]), pmul(b[0][k+2], b[1][j+2]))[:n]) if j != k else 0 for k in range(2*n-2*i)] for j in range(2*n-2*i)]
            else:
                b = [r[2:] for r in b[2:]]
        h += (-1)**(n - len(x)) * g[n]
    return h

```

Try it online!

Here is a faster version with some of the easy optimizations.

```
def hafnian(m):
  n = len(m)/2
  z = [[0]*(n+1) for _ in range(n*(2*n-1))]
  for j in range(1, 2*n):
    for k in range(j):
      z[j*(j-1)/2+k][0] = m[j][k]
  return solve(z, 2*n, 1, [1] + [0]*n, n)

def solve(b, s, w, g, n):
  if s == 0:
    return w*g[n]
  c = [b[(j+1)*(j+2)/2+k+2][:] for j in range(1, s-2) for k in range(j)]
  h = solve(c, s-2, -w, g, n)
  e = g[:]
  for u in range(n):
    for v in range(n-u):
      e[u+v+1] += g[u]*b[0][v]
  for j in range(1, s-2):
    for k in range(j):
      for u in range(n):
        for v in range(n-u):
          c[j*(j-1)/2+k][u+v+1] += b[(j+1)*(j+2)/2][u]*b[(k+1)*(k+2)/2+1][v] + b[(k+1)*(k+2)/2][u]*b[(j+1)*(j+2)/2+1][v]
  return h + solve(c, s-2, w, e, n)

```

Try it online!

For added fun, here is a reference implementation in J.
> 3 votes

# Answer
# Octave

This is basically a copy of Dennis' entry, but optimized for Octave. The main optimization is done by using the full input matrix (and its transpose) and recursion using only matrix indices, rather than creating reduced matrices.

The main advantage is reduced copying of matrices. While Octave does not have a difference between pointers/references and values and functionally only does pass-by-value, it's a different story behind the scenes. There, copy-on-write (lazy copy) is used. That means, for the code `a=1;b=a;b=b+1`, the variable `b` is only copied to a new location at the last statement, when it is changed. Since `matin` and `matransp` are never changed, they will never by copied. The disadvantage is that the function spends more time calculating the correct indices. I may have to try different variations between numerical and logical indices to optimize this.

Important note: input matrix should be `int32`! Save the function in a file called `haf.m`

```
function h=haf(matin,indices,matransp,transp)

    if nargin-4
        indices=int32(1:length(matin));
        matransp=matin';
        transp=false;
    end
    if(transp)
        matrix=matransp;
    else
        matrix=matin;
    end
    ind1=indices(1);
    n=length(indices);
    if n==2
        h=matrix(ind1,indices(2));
        return
    end
    h=0*matrix(1);
    for j=1:(n-1)
        indj=indices(j+1);
        k=matrix(ind1,indj);
        if logical(k)
            indicestemp=true(n,1);
            indicestemp(1:j:j+1)=false;
            h=h+k.*haf(matin,indices(indicestemp),matransp,~transp);
        end
    end
end

```

Example test script:

```
matrix = int32([0 0 1 -1 1 0 -1 -1 -1 0 -1 1 0 1 1 0 0 1 0 0 1 0 1 1;0 0 1 0 0 -1 -1 -1 -1 0 1 1 1 1 0 -1 -1 0 0 1 1 -1 0 0;-1 -1 0 1 0 1 -1 1 -1 1 0 0 1 -1 0 0 0 -1 0 -1 1 0 0 0;1 0 -1 0 1 1 0 1 1 0 0 0 1 0 0 0 1 -1 -1 -1 -1 1 0 -1;-1 0 0 -1 0 0 1 -1 0 1 -1 -1 -1 1 1 0 1 1 1 0 -1 1 -1 -1;0 1 -1 -1 0 0 1 -1 -1 -1 0 -1 1 0 0 0 -1 0 0 1 0 0 0 -1;1 1 1 0 -1 -1 0 -1 -1 0 1 1 -1 0 1 -1 0 0 1 -1 0 0 0 -1;1 1 -1 -1 1 1 1 0 0 1 0 1 0 0 0 0 1 0 1 0 -1 1 0 0;1 1 1 -1 0 1 1 0 0 -1 1 -1 1 1 1 0 -1 -1 -1 -1 0 1 1 -1;0 0 -1 0 -1 1 0 -1 1 0 1 0 0 0 0 0 1 -1 0 0 0 1 -1 -1;1 -1 0 0 1 0 -1 0 -1 -1 0 0 1 0 0 -1 0 -1 -1 -1 -1 -1 1 -1;-1 -1 0 0 1 1 -1 -1 1 0 0 0 -1 0 0 -1 0 -1 -1 0 1 -1 0 0;0 -1 -1 -1 1 -1 1 0 -1 0 -1 1 0 1 -1 -1 1 -1 1 0 1 -1 1 -1;-1 -1 1 0 -1 0 0 0 -1 0 0 0 -1 0 0 -1 1 -1 -1 0 1 0 -1 -1;-1 0 0 0 -1 0 -1 0 -1 0 0 0 1 0 0 1 1 1 1 -1 -1 0 -1 -1;0 1 0 0 0 0 1 0 0 0 1 1 1 1 -1 0 0 1 -1 -1 -1 0 -1 -1;0 1 0 -1 -1 1 0 -1 1 -1 0 0 -1 -1 -1 0 0 -1 1 0 0 -1 -1 1;-1 0 1 1 -1 0 0 0 1 1 1 1 1 1 -1 -1 1 0 1 1 -1 -1 -1 1;0 0 0 1 -1 0 -1 -1 1 0 1 1 -1 1 -1 1 -1 -1 0 1 1 0 0 -1;0 -1 1 1 0 -1 1 0 1 0 1 0 0 0 1 1 0 -1 -1 0 0 0 1 0;-1 -1 -1 1 1 0 0 1 0 0 1 -1 -1 -1 1 1 0 1 -1 0 0 0 0 0;0 1 0 -1 -1 0 0 -1 -1 -1 1 1 1 0 0 0 1 1 0 0 0 0 1 0;-1 0 0 0 1 0 0 0 -1 1 -1 0 -1 1 1 1 1 1 0 -1 0 -1 0 1;-1 0 0 1 1 1 1 0 1 1 1 0 1 1 1 1 -1 -1 1 0 0 0 -1 0])

tic
i=1;
while(toc<60)
    tic
    haf(matrix(1:i,1:i));
    i=i+1;
end

```

I have tried this out using TIO and MATLAB (I've actually never installed Octave). I imagine getting it to work is as simple as `sudo apt-get install octave`. The command `octave` will load the Octave GUI. If it's any more complicated than this, I will delete this answer until I've provided more detailed installation instructions.
> 1 votes

# Answer
# Rust

A port of Mr. Xcoder's example Python code. **Naive brute force, so slow.**

It needs much optimization.

### `src/main.rs`

```
extern crate permutohedron;
extern crate num_bigint;
extern crate num_traits;

use permutohedron::Heap;
use num_bigint::BigInt;
use num_traits::pow::Pow;
use num_traits::identities::One;
use num_traits::identities::Zero;

fn hafnian(matrix: Vec<Vec<i32>>) -> BigInt {
    let mut my_sum = BigInt::zero();
    let n = matrix.len() / 2;
    let mut data: Vec<usize> = (0..n*2).collect();
    let heap: Heap<'_, Vec<usize>, usize> = Heap::new(&mut data);

    for permutation in heap {
        let mut prod = BigInt::one();
        for j in 0..n {
            prod *= BigInt::from(matrix[permutation[2*j]][permutation[2*j+1]]);
        }
        my_sum += prod;
    }

    let factorial_n = (1..=n).fold(BigInt::one(), |f, i| f * BigInt::from(i));
    my_sum / (factorial_n * BigInt::from(2).pow(n as u32))
}

fn main() {
    println!("{:?}", hafnian(vec![
        vec![-1, 1, 1, -1, 0, 0, 1, -1],
        vec![1, 0, 1, 0, -1, 0, -1, -1],
        vec![1, 1, -1, 1, -1, -1, 0, -1],
        vec![-1, 0, 1, -1, -1, 1, -1, 0],
        vec![0, -1, -1, -1, -1, 0, 0, -1],
        vec![0, 0, -1, 1, 0, 0, 1, 1],
        vec![1, -1, 0, -1, 0, 1, 1, 0],
        vec![-1, -1, -1, 0, -1, 1, 0, 1]
    ]));

    println!("{:?}", hafnian(vec![
        vec![1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
        vec![1, 1, -1, 0, -1, 1, 1, 1, 0, -1],
        vec![0, -1, -1, -1, 0, -1, -1, 0, -1, 1],
        vec![0, 0, -1, 1, -1, 1, -1, 0, 1, -1],
        vec![0, -1, 0, -1, -1, -1, -1, 1, -1, 1],
        vec![0, 1, -1, 1, -1, 1, -1, -1, 1, -1],
        vec![0, 1, -1, -1, -1, -1, 1, 0, 0, 0],
        vec![1, 1, 0, 0, 1, -1, 0, 1, 1, -1],
        vec![0, 0, -1, 1, -1, 1, 0, 1, 1, 1],
        vec![0, -1, 1, -1, 1, -1, 0, -1, 1, 1]
    ]));

    println!("{:?}", hafnian(vec![
        vec![-1, 0, -1, -1, 0, -1, 0, 1, -1, 0, 0, 0],
        vec![0, 0, 0, 0, 0, -1, 0, 1, -1, -1, -1, -1],
        vec![-1, 0, 0, 1, 0, 0, 0, 1, -1, 1, -1, 0],
        vec![-1, 0, 1, -1, 1, -1, -1, -1, 0, -1, -1, -1],
        vec![0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1, 0],
        vec![-1, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 0],
        vec![0, 0, 0, -1, 0, 1, 1, -1, -1, 0, 1, 0],
        vec![1, 1, 1, -1, 0, 1, -1, 1, -1, -1, -1, -1],
        vec![-1, -1, -1, 0, 0, 1, -1, -1, -1, 1, -1, 0],
        vec![0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 1, 1],
        vec![0, -1, -1, -1, -1, 1, 1, -1, -1, 1, 0, -1],
        vec![0, -1, 0, -1, 0, 0, 0, -1, 0, 1, -1, 1]
    ]));

    println!("{:?}", hafnian(vec![
        vec![-1, 1, 0, 1, 0, -1, 0, 0, -1, 1, -1, 1, 0, -1],
        vec![1, -1, 1, -1, 1, 1, -1, 0, -1, 1, 1, 0, 0, -1],
        vec![0, 1, 1, 1, -1, 1, -1, -1, 0, 0, -1, 0, -1, -1],
        vec![1, -1, 1, -1, 1, 0, 1, 1, -1, -1, 0, 0, 1, 1],
        vec![0, 1, -1, 1, 0, 1, 0, 1, -1, -1, 1, 1, 0, -1],
        vec![-1, 1, 1, 0, 1, 1, -1, 0, 1, -1, -1, -1, 1, -1],
        vec![0, -1, -1, 1, 0, -1, -1, -1, 0, 1, -1, 0, 1, -1],
        vec![0, 0, -1, 1, 1, 0, -1, 0, 0, -1, 0, 0, 0, 1],
        vec![-1, -1, 0, -1, -1, 1, 0, 0, 1, 1, 0, 1, -1, 0],
        vec![1, 1, 0, -1, -1, -1, 1, -1, 1, 1, 1, 0, 1, 0],
        vec![-1, 1, -1, 0, 1, -1, -1, 0, 0, 1, -1, 0, -1, 0],
        vec![1, 0, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 1],
        vec![0, 0, -1, 1, 0, 1, 1, 0, -1, 1, -1, 1, 1, -1],
        vec![-1, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, -1, -1]
    ]));

}

```

### `Cargo.toml`

```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
# rand = "0.8.0"
# hyper = "0.13"
# tokio = { version = "0.2", features = ["full"] }
# rayon = "1.5.1"
# ndarray = "0.15.4"
# statrs = "0.13.0"
# ndarray-stats = "0.4.0"
# ndarray-linalg = "0.15"
# bitvec = "1.0.1"
# uint = "0.9"
# pariter = "0.5.1"
# rug = { version = "1.19.0", features = ["integer"], default-features = false }
# kd-tree = "0.5.1"
# time = "0.3"

permutohedron = "0.2.4"
num-bigint = "0.3.3"
num-traits = "0.2.14"

```

### Build and running

```
# win10 environment

$ cargo  build
$ target\debug\rust_hello.exe
BigInt { sign: Plus, data: BigUint { data: [4] } }
BigInt { sign: Minus, data: BigUint { data: [13] } }
......

```
> 0 votes

# Answer
# Mathematica

Use the recursive formula.

Try it online!

```
haf[matrix_?MatrixQ] :=
  haf[matrix] = Module[{n, h, j, copy}, n = Length[matrix];
    If[n == 2, Return[matrix[[1, 2]]]];
    h = 0;
    For[j = 2, j <= n, j++, If[matrix[[1, j]] == 0, Continue[]];
     copy = Delete[matrix, {{1}, {j}}];
     copy = Transpose[copy];
     copy = Delete[copy, {{1}, {j}}];
     h += matrix[[1, j]]*haf[copy];];
    h];

```
> 0 votes

---
Tags: math, fastest-code, linear-algebra
---


# Question
Title: It's [current year] already, folks, go home
On most challenges when it is currently not the corresponding year of the challenge, It says this in the front.

> It's \[current year\] already, folks, go home.

You have to output this text with the current year substituted.

---

# I/O

**Input:** None.

**Output**: `It's [current year] already, folks, go home.`

# Answer
# bash + date, 40 bytes

```
date +"It's %Y already, folks, go home."

```

Try it online!
> 18 votes

# Answer
# C (gcc), 58 bytes

```
f(){printf("It's%s already, folks, go home.",__DATE__+6);}

```
> 17 votes

# Answer
# 05AB1E, ~~21~~ 20 bytes

Saved a byte thanks to *Erik the Outgolfer*

```
žg“It's ÿˆ§,¹Ò,‚œ€¨.

```

Try it online!
> 15 votes

# Answer
# TeX (44 bytes)

```
It's \the\year\ already, folks, go home.\bye

```
> 14 votes

# Answer
# PHP, 42 bytes

```
It's <?=date(Y)?> already, folks, go home.

```
> 12 votes

# Answer
# Bash, 45 characters

```
printf "It's %(%Y)T already, folks, go home."

```

Bash's built-in `printf` in version 4.2 got the `%(fmt)T` format specifier and since version 4.3 it defaults to current timestamp in absence of argument.

Sample run:

```
bash-4.3$ printf "It's %(%Y)T already, folks, go home."
It's 2017 already, folks, go home.

```
> 8 votes

# Answer
## Batch, 45 bytes

```
@echo It's %date:~6% already, folks, go home.

```

Batch is actually reasonably competitive for once.
> 6 votes

# Answer
## Mathematica, 53 bytes

```
Print["It's ",Now[[1,1]]," already, folks, go home."]

```
> 6 votes

# Answer
# Python 2, 67 bytes

```
import time
print"It's",time.gmtime()[0],"already, folks, go home."

```

Try it online!
> 5 votes

# Answer
# x86 machine code on DOS - 62 bytes

```
00000000  b4 04 cd 1a bf 23 01 88  c8 24 0f 00 05 4f c1 e9  |.....#...$...O..|
00000010  04 75 f4 ba 1b 01 b4 09  cd 21 c3 49 74 27 73 20  |.u.......!.It's |
00000020  30 30 30 30 20 61 6c 72  65 61 64 79 2c 20 66 6f  |0000 already, fo|
00000030  6c 6b 73 2c 20 67 6f 20  68 6f 6d 65 2e 24        |lks, go home.$|
0000003e

```

Even though the input from the BIOS is in BCD (as opposed to the plain 16 bit value got from the equivalent DOS call), decoding it to ASCII turned out to be almost as long as base-10 printing a register. Oh well.

```
    org 100h

section .text

start:
    mov ah,4
    int 1ah             ; get the date from BIOS; cx now contains the year in packed BCD
    mov di,placeholder  ; put di on the last character of placeholder
lop:
    mov al,cl
    and al,0xf  ; get the low nibble of cx
    add [di],al ; add it to the digit
    dec di      ; previous character
    shr cx,4    ; next nibble
    jnz lop     ; loop as long as we have digits to unpack in cx
    mov dx,its
    mov ah,9
    int 21h     ; print the whole string
    ret

its:
    db "It's 000"
placeholder:
    db "0 already, folks, go home.$"

```
> 5 votes

# Answer
## Ruby, 52 bytes

```
puts"It's #{Time.now.year} already, folks, go home."

```
> 4 votes

# Answer
# CJam, 38 bytes

```
"It's "et0=" already, folks, go home."

```

Try it online!
> 4 votes

# Answer
# Mathematica, 58 bytes

```
"It's "<>ToString@#<>" already, folks, go home."&@@Date[]&

```

Anonymous function. Takes no input and returns a string as output. No, I'm not going to make a REPL submission, post it yourself if that one byte is so important.
> 4 votes

# Answer
# Perl 6,  ~~53~~  51 bytes

```
say "It's {Date.today.year} already, folks, go home."

```

Try it

```
say "It's {now.Date.year} already, folks, go home."

```

Try it
> 3 votes

# Answer
# TI-Basic (TI-84 Plus CE with OS 5.2+), 64 bytes

```
getDate
"It's "+toString(Ans(1))+" already, folks, go home.

```

TI-Basic is a tokenized language. Some commands (`getDate`, `toString(`, etc.), and all lowercase letters are two-bytes and everything else used here is one byte each.

Explanation:

```
getDate                                             # 3, store {Y,M,D} in Ans
"It's "+toString(Ans(1))+" already, folks, go home. # 61, implicitly return required string with Y from getDate

```

# TI-Basic (TI-84 Plus CE with OS 5.1), 108 bytes

```
{0,1→L<sub>1</sub>
getDate
Ans(1)L<sub>1</sub>→L<sub>2</sub>
LinReg(ax+b) Y<sub>1</sub>
Equ►String(Y<sub>1</sub>,Str0
sub(Str0,1,length(Str0)-3→Str0
"It's "+Str0+" already, folks, go home.

```

TI-Basic is a tokenized language. The more complicated user variables (`Y<sub>1</sub>`, `L<sub>1</sub>`, `L<sub>2</sub>`, `Str0`), some commands (`LinReg(ax+b` , `getDate`, `sub(`, `Equ►String(`, `length(`), and all lowercase letters are two-bytes and everything else used here is one byte each.

OS 5.2 added a `toString(` command, which obsolesces about half of this submission, which is based off of this algorithm.

Explanation:

```
{0,1→L<sub>1</sub>                                  # 8 bytes
getDate                                  # 3 bytes, store {Y,M,D} list in Ans
Ans(1)L<sub>1</sub>→L<sub>2</sub>                              # 10 bytes, multiply L<sub>1</sub> by the year and store in L<sub>2</sub>
LinReg(ax+b) Y<sub>1</sub>                          # 5 bytes, take a linear regression of the points specified by each pair of corresponding coordinates in L<sub>1</sub> and L<sub>2</sub> and store it in Y<sub>1</sub>
Equ►String(Y<sub>1</sub>,Str0                       # 8 bytes, convert Y<sub>1</sub> to a string
sub(Str0,1,length(Str0)-3→Str0           # 18 bytes, remove the "X+0" from LinReg
"It's "+Str0+" already, folks, go home.  # 56 bytes, implicitly return the required output
```
> 3 votes

# Answer
# JavaScript ES6, 56 bytes

```
_=>`It's ${Date().split` `[3]} already, folks, go home.`

```

### Try it online!

```
const f = _=>`It's ${Date().split` `[3]} already, folks, go home.`

console.log(f())
```
> 3 votes

# Answer
# R, ~~62 59~~ 62 bytes

```
cat("It's",format(Sys.time(),"%Y"),"already, folks, go home.")

```
> 3 votes

# Answer
## PowerShell 3.0, 44 bytes

```
"It's $(date|% y*) already, folks, go home."

```

PowerShell is competing quite well today!
> 3 votes

# Answer
# Japt, 31 bytes

```
`It's {Ki} alÎ%y, folks, go Êà.

```

Try it online!
> 3 votes

# Answer
# Vyxal, ~~39~~ 27 bytes

```
`It's % ×ġ, ṗḊ, go λ∵.`kðt%

```

Try it Online!

Surely golfable?
> 3 votes

# Answer
# C#, 58 bytes

```
()=>"It's "+DateTime.Now.Year+" already, folks, go home.";

```

Anonymous function which returns the required string.

Full program:

```
using System;

public class Program
{
    public static void Main()
    {
        Func<string> f=
        ()=>"It's "+DateTime.Now.Year+" already, folks, go home.";

        Console.WriteLine(f());
    }
}

```
> 2 votes

# Answer
# Pyth, 38 bytes

```
s["It's ".d3" already, folks, go home.

```

Online interpreter.
> 2 votes

# Answer
# JavaScript, ~~77~~ ~~71~~ ~~67~~ 63 bytes

```
alert("It's "+Date().split(' ')[3]+" already, folks, go home.")
```

Thanks to @programmer5000 for the spaces!

# JavaScript ES6 ~~66~~ 60 bytes

```
alert(`It's ${Date().split` `[3]} already, folks, go home.`)
```
> 2 votes

# Answer
# Haskell, 113 bytes

```
import Data.Time.Clock
f=do t<-getCurrentTime;putStr$"It's "++(fst.span(>'-').show)t++" already, folks, go home."

```

Try it online! Replace `f` with `main` for a full program.

The function `getCurrentTime` returns a `UTCTime` object which looks something like `"2017-04-02 10:22:29.8550527 UTC"` when converted to a string by `show`. `fst.span(>'-')` takes the leading characters while they are larger than `'-'`, that is the current year. For the next 7972 years `take 4` would work for 8 bytes less, but we want our code to work correctly for ever and ever.

As far as I see build-in functions to get the current year require a `import Data.Time.Calendar`, so extracting the year from the string should be the shortest option.
> 2 votes

# Answer
# Befunge-98, ~~57~~ 55 bytes

```
"emoh og ,sklof ,ydaerla@ s'tI"4k,y\4*:*/"&2"*+.f7+k,@

```

Try it online!

Thanks to James Holderness for pointing out my mistake with the sysinfo instruction.

`"emoh og ,sklof ,ydaerla@ s'tI"` pushes the sentence to the stack where `4k,` prints the first word. `y` is the sysinfo instruction. When passed 20 (the unprintable in the string), it returns `256*256*(year-1900) + 256*month + day of month`. `\4*:*/"&2"*+.` takes just the year from the value and prints it and`f7+k,` prints the rest of the sentence.
> 2 votes

# Answer
# JavaScript ES6, ~~63~~ 62 bytes

```
_=>`It's ${new Date().getFullYear()} already, folks, go home`

```
> 1 votes

# Answer
# Python 3, ~~73~~ 68 bytes

```
import time
print(time.strftime("It's %Y already, folks, go home."))

```

Very basic answer. The "%Y" gets the current year.

*Thanks to @ovs for removing 5 bytes*
> 1 votes

# Answer
## QBIC, 48 bytes

```
?@It's `+right$(_D,4)+@ already, folks, go home.

```

I really should start working on substring...

Explanation:

```
?       PRINT
@ ... ` String literal:
        - creates a string with all the text from @ to `,
        - stores it as the first available string var (A$)
        - and injects A$ at the current point in the QBasic translated code.
+       String concatenation
right$  QBasic function to take characters from the right.
_D      QBIC's call to get the system date as dd-mm-yyyy (_d gets the time)
+@ ...  Second string lit (B$). Doesn't need the closing ` because of EOF.

```

Update: Substring saves me 4 bytes:

```
?@It's `+_s_D,-4|+@ already, folks, go home.

```
> 1 votes

# Answer
# GolfScript, 48 bytes

```
"It's #{Time.new.year} already, folks, go home."

```

Try it online!

Yes, this is string interpolation.
> 1 votes

# Answer
# MATL, 42 bytes

```
'It''s '1&Z'V' already, folks, go home.'&h

```

Try it online!

```
'It''s '                      % Push this string
1&Z'                          % Push current year
V                             % Convert to string
' already, folks, go home.'   % Push this string
&h                            % Concatenate all stack contents horizontally
                              % Implicitly display

```
> 1 votes

# Answer
# APL (Dyalog), ~~44~~ 40 bytes

*4 saved thanks to Uriel by rearranging the structure*

```
¯5⌽'already, folks, go home.It''s',1⊃⎕ts

```

Try it online!

### Explanation

```
'alrea ... It''s', ⍝ "alrea .. It's" concatenated with
1⊃⎕ts              ⍝ the first element in the ⎕ts (contains the year)
¯5⌽                ⍝ rotated 5 times to the right

```
> 1 votes

# Answer
## IBM/Lotus Notes Formula, 54 bytes

Not exactly challenging but here we go anyway...

```
"It's "+@Text(@Year(@Now))+" already, folks, go home."

```
> 1 votes

# Answer
# Java 8, ~~81~~ 78 bytes

```
()->System.out.print("It's "+java.time.Year.now()+" already, folks, go home.")

```
> 1 votes

# Answer
**VBScript, 53 bytes**

```
msgbox"It's "&year(now())&" already, folks, go home."

```
> 1 votes

# Answer
## T-SQL, 66 bytes

```
print concat('It''s ',year(getdate()),' already, folks, go home.')

```
> 1 votes

# Answer
# SmileBASIC, 65 bytes

**Edit:** This one should handle years of any size, even though SB (as far as I'm aware) doesn't support any year that isn't 4 characters.

```
?"It's "+LEFT$(DATE$,INSTR(DATE$,"/"))+" already, folks, go home.

```
> 1 votes

# Answer
# Javascript, 67 bytes

```
alert("It's "+new Date().getFullYear()+" already, folks, go home.")

```
> 1 votes

# Answer
# Noodel, 34 bytes

```
Ƈƈy”VẠṇ`DðC1}816ṚĊC:@-~ḂC'^D^#8Ụ İ

```

Try it:)

---

## How it works

```
Ƈƈy”VẠṇ`DðC1}816ṚĊC:@-~ḂC'^D^#8Ụ İ
Ƈƈy                                # Gets the current year.
Ƈ                                  # Gets the current time as an integer.
 ƈy                                # Takes the integer and gets the current year from it.

   ”VẠṇ`DðC1}816ṚĊC:@-~ḂC'^D^#8Ụ İ # Creates the string.
   ”VẠṇ`DðC1}816ṚĊC:@-~ḂC'^D^#8Ụ   # Pushes on the string "It's¤ð¤already,¤folks,¤go¤home." as an array splitting on the "ð" character where "¤" is a space.
                                   # (space) NOOP that separates commands.
                                 İ # Concatenate the array using the current year.
                                   # Implicitly print to the screen.

```

```
<div id="noodel" code="Ƈƈy”VẠṇ`DðC1}816ṚĊC:@-~ḂC'^D^#8Ụ İ" input="" cols="40" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 1 votes

# Answer
# Excel, 48 bytes

```
="It's "&YEAR(NOW())&" already, folks, go home."

```
> 1 votes

# Answer
# SmileBASIC, 51 bytes

```
?"It's ";LEFT$(DATE$,4);" already, folks, go home.

```

I don't think it's reasonable to ever expect support for 5 digit years, but if SB gets updated in 10 millennia, then this should work for 1 extra byte:

```
DTREAD OUT Y,,?"It's ";Y;" already, folks, go home.

```
> 1 votes

# Answer
# Aceto, ~~39~~ 38 + 1 for (-l flag) ~~40~~ 39 bytes

```
τ"It's "pp" already, folks, go home."p

```

Try it online!

Saved one byte thanks to DLosc

```
τ"It's "pp" already, folks, go home."p
τ                 push local datetime on stack
"..."             push the first part of the string
     pp           print both
       "..."      second part of string
            p     print it

```
> 1 votes

# Answer
# SenseTalk, 47 bytes

```
put "It's"&&the year&&"already, folks, go home"

```
> 1 votes

# Answer
# Factor, 49 bytes

```
now year>> [I It's ${} already, folks, go home.I]

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2, 26 bytes

```
‘It's % ¥Ƙ, ⁶Ẇ, go ⱮŻ.‘kO%

```

Attempt This Online!

#### Explanation

```
‘...‘kO%  # Full program
‘...‘     # Compressed string "It's % already, folks, go home."
     kO%  # Replace the "%" with the current year
          # Implicit output

```
> 1 votes

# Answer
# Gawk, 64 60 bytes

GNU Awk has a couple of built-in function to get current time and date.

```
BEGIN{print"It's "strftime("%Y")" already, folks, go home."}

```

**Edit**

The script can run from a file (`-f`), which saves 4 bytes (thanks **manatwork**).
> 0 votes

# Answer
# Emacs/Lisp, 70 bytes

```
(concat "It's " (format-time-string "%Y") " already, folks, go home.")

```
> 0 votes

# Answer
# Lua, 59 bytes

Gets the system date

```
print("It's "..os.date('%Y').." already, folks, go home.")

```
> 0 votes

# Answer
## REXX, 53 bytes

```
say "It's" left(date(s),4) "already, folks, go home."

```
> 0 votes

# Answer
# Fourier, 101 bytes

```
73a116a39a115a32a~S5do32a97a108a+6a101a-4a+3a121a44aSa102a+9~Aa-3a-1a+8a44aSa103a+8aSa104aAa-2a-8a46a

```

Try it online!
> 0 votes

# Answer
# T-SQL 74 bytes

```
print 'It''s '+CAST(year(GETDATE())as varchar)+' already, folks, go home.'

```

Appreciate that there is a shorter answer above but in the event that you're in the SQL-Server dark ages and don't have CONCAT available this will work :)
> 0 votes

# Answer
# AHK 43 bytes

```
Send,It's %A_Year% already, folks, go home.

```
> 0 votes

# Answer
# Tcl, 63

No chance of ever winning

```
puts "It's [clock f [clock se] -f %Y] already, folks, go home."

```

demo
> 0 votes

# Answer
# Forth, 49 bytes

I tried leaving off the trailing `"` and it worked. Cool.

```
." It's " time&date . ." already, folks, go home.

```

**Try it online**

> `time&date`*nsec nmin nhour nday nmonth nyear*
> Report the current time of day. Seconds, minutes and hours are numbered from 0. Months are numbered from 1. - Source
> 0 votes

# Answer
# SQLite, 65 bytes

```
SELECT"It's "||strftime('%Y','now')||' already, folks, go home.';

```

Try it online!
> 0 votes

# Answer
# Processing.org 48 bytes

```
print("It's",year(),"already, folks, go home.");

```
> 0 votes

# Answer
# Jekyll, 35 bytes

Jekyll is a static site generator and it's the backend of GH Pages. *If only* it counts as a language here.

```
It's :year already, folks, go home.

```
> 0 votes

# Answer
## Pyth, 38 bytes

```
%"It's %d already, folks, go home.".d3

```

Try it online!
> 0 votes

# Answer
# VBA, 56 Bytes

```
MsgBox "It's " & Year(Now) & " already, folks, go home."

```
> 0 votes

# Answer
# Excel VBA, 44 Bytes

Not sure if this is a cheat... assuming "It's" in in cell A1 on an Excel worksheet and " already, folks, go home." is in A3:

```
Msgbox Range("A1") & Year(Now) & Range("A3")

```
> 0 votes

# Answer
**VBA (Excel), 42 bytes**

Using Immediate Window.

`?"It's"year(now)"already, folks, go home."`
> 0 votes

# Answer
# Attache, 47 bytes

```
C!DateFormat!"It's %Y already, folks, go home."

```

Try it online!

This is a constant function that returns the year it was defined in. Alternatively, a function that returns the year it was called in:

```
{DateFormat!"It's %Y already, folks, go home."}

```

And for an extra byte:

```
"It's %s already, folks, go home."%Date[].year|C

```

or

```
{"It's %s already, folks, go home."%Date[].year}

```

Nothing too special going on here in either case.
> 0 votes

# Answer
# Python 2, 90 86 83 78 bytes

```
from datetime import*;print"It's",date.today().year,"already, folks, go home."

```

EDIT: Shaved off a couple of bytes.

EDIT: Shaved off more thanks to @HyperNeutrino
> 0 votes

# Answer
# SOGL V0.12, ~~24~~ 22 bytes

```
uS"³9n⁶=⅛8!⅔ηεēæ▼∙Ω╝‘⁽

```

Try it Here!
> 0 votes

# Answer
# jq, 52 characters

(48 characters code + 4 characters command line options)

```
now|strftime("It's %Y already, folks, go home.")

```

Sample run:

```
bash-4.4$ jq -nr 'now|strftime("It'"'"'s %Y already, folks, go home.")'
It's 2018 already, folks, go home.

```

Try it online!
> 0 votes

# Answer
# Gema, 63 characters

```
\A=@subst{<D4>=It's \$0 already, folks, go home.\;?=;@date}@end

```

Sample run:

```
bash-4.4$ gema '\A=@subst{<D4>=It'"'"'s \$0 already, folks, go home.\;?=;@date}@end'
It's 2018 already, folks, go home.

```
> 0 votes

# Answer
# jamal, 56 characters

```
{@format date=YEAR}It's {@date} already, folks, go home.

```

Sample run:

```
bash-4.4$ perl jamal.pl year.jam
It's 2018 already, folks, go home.

```
> 0 votes

# Answer
# Arturo, 47 bytes

```
clip~"It's |now\year| already, folks, go home."

```

Try it!

Outputs to clipboard. The link includes a stdout version too.
> 0 votes

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