title: Word Poker, Who Wins?

text:
# Question
Title: Word Poker, Who Wins?
The input will be two five letter words. They don't actually have to be dictionary words, just any five letters each, all lowercase or all uppercase, your choice. Only A-Z will appear in the input words and they will always be 5 characters in length.

Your program is to score them both as though they were poker hands and output the higher hand. Of course suits won't apply here, only rankings so there's no flushes.

The typical poker ranking system goes: '1 pair', '2 pairs', '3 of a kind', 'straight', 'full house', '4 of a kind', '5 of a kind', and of course there is the possibility the hand (or word in this case) could be worth nothing.

**In the case of ties**, letters closer to A are considered higher, so a pair of As beats a pair of Bs. In some cases both hands might be identical, but in a different order (or not), in that case output either hand or a resorted version of it.

This external page contains information about how to identify the winner and especially addresses ties within the specific rankings, in case you aren't familiar with how to score poker hands.

**In the case of straights**: the letters must be adjacent in the alphabet and are not allowed to wrap around. So 'defgh' in any order is a straight, 'xyzab' is not.

Examples of how to score a single hand:

```
word   | scored as
---------------------
ccccc  | 5 of a kind     <-- highest ranking
woooo  | 4 of a kind
opopo  | full house
vurst  | straight
vovvu  | 3 of a kind
ppoww  | 2 pairs
upper  | 1 pair
kjsdf  | high card only (in this case D) <-- lowest ranking

```

So the program will actually produce results like this:

```
input        |  output
-----------------------
voviu,kjsdf  |  voviu     because a pair beats nothing
opoqo,upper  |  opoqo     because 3 of a kind beats a pair
woooo,ggegg  |  ggegg     because 4 Gs beats 4 Os
queue,hopup  |  queue     because 2 pairs beats 1 pair
lodpl,ddkop  |  ddkop     because pair DD beats pair LL
huhyg,hijht  |  huhyg     both have pair HH, but G beats I
ddffh,ccyyz  |  ccyyz     both have 2 pairs, but CC(yyz) beats DD(ffh)
okaok,nkunk  |  nkunk     KK ties with KK, but NN beats OO
abcdf,bcdef  |  bcdef     because it is a straight
qtery,retyq  |  qtery     identical! so doesnt matter
abedc,vyxwz  |  abedc     because it is a "higher" straight
hhhij,hijkl  |  hijkl     because straight beats 3 of a kind
aaabb,zzzzz  |  zzzzz     because nothing beats 5 of a kind

```

The order of the letters in both the input and output are irrelevant, so the order in your output can be different than the input, but the same inventory of letters needs to be present.

The output must contain exactly five letters -- no more, no less.

The usual codegolf rules apply. Shortest code wins.

# Answer
## JavaScript (~~224~~ ~~218~~ 213 bytes)

```
s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

```

**Ungolfed:**

```
s=>t=>(
  v=s=>(
    o={},
    l=n=0,
    z=3.5,
    [...s].sort().map(c=>(
      n+=o[c]=-~o[c],
      z*=!l|l+1==(l=c.charCodeAt())
    )),
    [n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]
  ),
  w=v(s),x=v(t),
  w[0]>x[0] || w[0]==x[0] && w[1]<x[1] ? s : t
)

```

After `map()` runs, `n + z` determines the ranking of a hand:

(You can understand why I initialized `z` to 3.5.)

In case of a tie, `Object.keys(o).sort()` is used to determine the higher ranking hand.

**Snippet:**

```
f=

s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

console.log(/voviu/.test(f('voviu')('kjsdf')))       //because a pair beats nothing
console.log(/opoqo/.test(f('opoqo')('upper')))       //because 3 of a kind beats a pair
console.log(/ggegg/.test(f('woooo')('ggegg')))       //because 4 Gs beats 4 Os
console.log(/queue/.test(f('queue')('hopup')))       //because 2 pairs beats 1 pair
console.log(/ddkop/.test(f('lodpl')('ddkop')))       //because pair DD beats pair LL
console.log(/huhyg/.test(f('huhyg')('hijht')))       //both have pair HH, but G beats I
console.log(/ccyyz/.test(f('ddffh')('ccyyz')))       //both have 2 pairs, but CC(yyz) beats DD(ffh)
console.log(/nkunk/.test(f('okaok')('nkunk')))       //KK ties with KK, but NN beats OO
console.log(/bcdef/.test(f('abcdf')('bcdef')))       //because it is a straight
console.log(/qtery|retyq/.test(f('qtery')('retyq'))) //identical! so doesnt matter
console.log(/abedc/.test(f('abedc')('vyxwz')))       //because it is a "higher" straight
console.log(/hijkl/.test(f('hhhij')('hijkl')))       //because straight beats 3 of a kind
console.log(/zzzzz/.test(f('aaabb')('zzzzz')))       //because nothing beats 5 of a kind
```
> 4 votes

# Answer
# Jelly,  ~~28 27 29~~  27 bytes

+2 & then -2 fix a bug, then re-golf.

```
FI=1ȦḤW
OµNĠLÞṚịµL€+Ç,N
ÇÞṪ

```

A monadic link taking a list of "hands" and returning (one of) the winners.

Works for all-uppercase OR all-lowercase input.
(...but not mixed, for that prepend the final line with `Œl` or `Œu`).

**Try it online!** or see the test suite.

### How?

```
FI=1ȦḤW - Link 1, straight offset: grouped and reverse sorted hand ordinals
        -                     e.g. [[-101],[-100],[-99],[-98],[-97]]
F       - flatten                  [-101,-100,-99,-98,-97]
 I      - increments               [1,1,1,1]
  =1    - equal 1? (vectorises)    [1,1,1,1]
    Ȧ   - any and all?             1
     Ḥ  - double                   2
      W - wrap in a list           [2]
        -   The purpose of this is so that when "a" from Link 2 represents a straight we
        -   get [2], whereas for any other hand we get [0]. Adding the [2] to [1,1,1,1,1]
        -   (the lengths of a straight's groups) yields [3,1,1,1,1], placing it between
        -   three of a kind, [3,1,1], and a full house, [3,2], as required.

OµNĠLÞṚịµL€+Ç,N - Link 2, hand rank key function: list of characters       e.g. "huhyg"
O               - cast to ordinals                                [104,117,104,121,103]
 µ              - monadic chain separation, call that o
  N             - negate (to give them a reverse-sort order) [-104,-117,-104,-121,-103]
   Ġ            - group indices by value                            [[4],[2],[1,3],[5]]
     Þ          - sort by key function:
    L           -   length                                          [[4],[2],[5],[1,3]]
      Ṛ         - reverse                                           [[1,3],[5],[2],[4]]
       ị        - index into o                       [[-104,-104],[-103],[-117],[-121]]
        µ       - monadic chain separation (call that a)
         L€     - length of €ach                                              [2,1,1,1]
            Ç   - call last link (2) as a monad -> [isStraight? * 2]                [0]
           +    - addition (vectorises)                                       [2,1,1,1]
              N - negate o                                [[104,104],[103],[117],[121]]
             ,  - pair                        [[2,1,1,1],[[104,104],[103],[117],[121]]]
                -   now sorting by this will first be comparing the hand class, and if
                -   and only if they match comparing the card values in the required order.

ÇÞḢ - Main link: list of lists of characters (list of hands)
 Þ  - sort by key function:
Ç   -   last link (2) as a monad
  Ṫ - tail (best or an equal-best hand)

```
> 3 votes

# Answer
## JavaScript (250 247 232 bytes)

```
S=d=>(x={},l=99,h=s=0,[...d].map(v=>x[v]=-~x[v]),Object.keys(x).map(v=>(c=91-v.charCodeAt(),t=x[v],s+=1e4**t,c<x[t]?0:x[t]=c,g=(h=c>h?c:h)-(l=c<l?c:l))),[5,4,3,2,1].map(v=>s+=0|x[v]**v),s+(s<5e7&&g<5?1e13:0)),C=a=>b=>(S(a)>S(b)?a:b)

```

### Ungolfed code & test cases in JSFiddle: https://jsfiddle.net/CookieJon/8yq8ow1b/

Saved some bytes with thanks to @RickHitchcock. @StephenS & @Arnauld
> 3 votes

# Answer
# Python 2.7, ~~242~~ 223 bytes

```
from collections import*
s=sorted
f=lambda x,y:s(map(lambda h:(lambda (r,n):((3,1.5)if len(r)==5 and ord(r[0])+4==ord(r[4])else n,[-ord(d) for d in r],h))(zip(*s(Counter(h).items(),key=lambda z:(-z[1],z[0])))),(x,y)))[1][2]

```

Similar in basic concept to the javascript examples (sort by hand strength with an exception for straights; then by rank); but taking advantage of `collections.Counter` Unfortunately, `.most_common` doesn't have quite the desired behavior; so had to add a custom sort key.

Edit: a bit more code golfing to trim down 19 bytes.

**Un-golfed code**

```
from collections import Counter

def convertHand(h):
    # first get item counts, appropriately ordered; e.g. cbabc -> (('b',2), ('c',2),('a',1))
    sortedPairs = sorted(Counter(h).items(),key=lambda x:(-x[1],x[0]))

    # 'unzip' the tuples to get (('b','c','a'), (2,2,1))
    ranks, numberFound = zip(*sortedPairs)

    if len(ranks)==5:
        # no pairs; is it a straight? well, since they are in increasing order...
        if ord(ranks[0])+4 == ord(ranks[4]):
            # replace numberFound with something that will sort above 3 of a kind but below full house
            numberFound = (3,1.5)

    # invert the values of the ranks, so they are in decreasing, rather then increasing order
    ranks = [-ord(r) for r in ranks]

    # arrange tuples so we can sort by numberFound, and then ranks; and keep a reference to the hand
    return (numberFound, ranks, h)

# put it all together...
def f(x,y):
    hands = [convertHand(h) for h in (x,y)]
    rankedHands = sorted(hands)
    return rankedHands[1][2]

```
> 2 votes

# Answer
## Mathematica, 635 bytes

```
H[x_]:=Block[{t},T=Sort@ToCharacterCode[x];L=Last/@Tally@T;t=0;S=Count;If[S[L,2]==1,t=1];If[S[L,2]==2,t=2];If[S[L,3]==1,t=3];If[S[Differences@T,1]==4,t=4];If[S[L,2]==1&&S[L,3]==1,t=5];If[S[L,4]==1,t=6];If[S[L,5]==1,t=7];t];F[K_,v_]:=First@Flatten@Cases[Tally@K,{_,v}];B=ToCharacterCode;(Z=Sort@B@#1;Y=Sort@B@#2;a=H[#1];b=H[#2];If[a>b,P@#1,If[a<b,P@#2]]If[a==b&&a==0,If[Z[[1]]<Y[[1]],P@#1,P@#2]];If[a==b&&(a==1||a==2),If[F[Z,2]<F[Y,2],P@#1,If[F[Z,2]==F[Y,2],If[F[Z,1]<F[Y,1],P@#1,P@#2],P@#2]]];If[a==b&&(a==3||a==5),If[F[Z,3]<F[Y,3],P@#1,P@#2]];If[a==b&&a==6,If[F[Z,4]<F[Y,4],P@#1,P@#2]];If[a==b&&(a==7||a==4),If[Tr@Z<Tr@Y,P@#1,P@#2]])&

```

.
.
**Input form**

> \["abcde", "kkekk"\]
> 1 votes

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


title: Alice's ordinal formatting

text:
# Question
Title: Alice's ordinal formatting
# Introduction

Alice is a 2-d language by Martin Ender which has two different execution modes, *cardinal* and *ordinal*. When the instruction pointer passes *through* a mirror (either `/` or `\`), it switches from one mode to the other one.

In this challenge we will focus on *ordinal* mode, where commands operate on strings and the instruction pointer moves diagonally, bouncing against the edges of the code.

Simple programs operating only in ordinal mode can be written in a quite compact style, like in the following example:

```
/fbd/
@aec\

```

Here the IP starts in cardinal mode from the first cell going east, passes through the first mirror and starts moving diagonally and bouncing, executing commands `a`, `b`, and `c`. It then encounters the north-east mirror which makes it go south towards the other mirror and then start bouncing back towards the west, encountering commands `d`,`e`,`f`, and finally `@`, which terminates the program.

This kind of structure is quite compact, but it's not easy to write and maintain (adding a single command might force us to reorder most of the code!), so I'd like you to help me with formatting.

# The task

Given a sequence of commands, where each command is a single printable ASCII character, reorder them on two lines so that the first half of the sequence can be read starting from the first character of the second line and then moving always diagonally towards the right, while the second half can be read taking the remaining characters from right to left. Don't worry about mirrors and the termination symbol, I'll add them myself.

So, for example, given input `abcdef` you should output

```
fbd
aec

```

In case the input is of odd length, you should add a single space (which is a noop in Alice) anywhere, as long as the sequence of commands encountered remains the same. You can also choose to output two lines differing in length by one character, in which case the shorter one is considered as having a single space at the end.

# Rules

This is , the shortest answer, in bytes, wins!

* You may input/output via any of the default input/output methods
* Input consists of a single line of printable ASCII characters
* A single trailing newline is permitted in the output
* Some outputs of your program may not have a completely correct behavior when run as Alice programs (e.g. if the padding space is inserted inside a string literal). You don't have to concern yourself with these situations
* Standard loopholes are forbidden

# Test cases

```
--Input
abcdef
--Output
fbd
aec

--Input
123
--Output
 2
13
OR
31
 2
OR
3
12
OR
32
1

--Input
O
--Output
O

OR

O

--Input
"Hello, World!"o
--Output
oH!lloo
""edlr,W

--Input
i.szR.szno
--Output
o.zz.
inssR

--Input
"  ^^} .~[}.~~[}{~~{}[^^^^.""!}"r.h~;a*y'~i.*So
--Output
o *^i}'.*[;.h~r}}~"{.[^
"S .^~ y~a}~~.["{!~"}^^^
(Odd length, your solution may be different)

```

# Answer
# Jelly, 15 bytes

```
œs2U2¦ṚZUJḤ$¦ZY

```

Try it online!

Takes quoted input.

Explanation:

```
œs2U2¦ṚZUJḤ$¦ZY Main link, monadic
œs2             Split into 2 chunks of similar lengths, last might be shorter
   U2¦          Reverse the 2nd chunk
      Ṛ         Swap the chunks
       Z        Transpose into chunks of length 2
        UJḤ$¦   Reverse the chunks at even indices (1-indexed)
             Z  Transpose into 2 chunks again
              Y Join by a newline

```
> 1 votes

# Answer
## Alice, 28 bytes

```
/mY. zm~wZ.k;
\I;'!*?RR.OY@/

```

Try it online!

If the input length is odd, this puts the padding space at the end of the linearised program, which ends up being the first character of the output.

Leo wrote an Ordinal formatter in Alice a few days ago. After adding support for odd-length inputs and then removing some stuff that wasn't necessary for this challenge, we ended up at 28 bytes. I wanted to try a slightly different approach, which is this answer. Unfortunately, it just ended up tying 28 bytes, but at least this way I can post my own solution and let Leo post his original algorithm.

This does use Leo's really clever idea to split a string in half with `..Y;m;.!z?~`.

### Explanation

Let's assume that the input has even length (because we'll just pad it with a space if it doesn't). The pattern is a bit easier to see if we use `0123456789` as the code. The required output would be:

```
91735
08264

```

So the first line contains all odd positions of the input and the second line all the even inputs. Furthermore, if we reverse the odd positions, then the lines itself are both the first half (possibly longer) interleaved with the reverse of second half.

So the basic idea is:

* Separate input into odd and even positions.
* Pad the odd positions with a space if necessary.
* Reverse the odd positions.
* Then twice: halve the current string, reverse the second half, interleave both halves, print with trailing linefeed.

As for the code, this looks a lot like the kind of layout we're producing in this challenge, but it's subtly different: when the IP hits the `/` at the end of the code it gets reflected *east*, not south. Then, while in Cardinal mode, the IP will wrap around to the first column. The `\` there re-enters Ordinal mode, so that the second half of the code doesn't go from right to left here, but from left to right as well. This is beneficial when working with the return address stack, because it doesn't store information about the IP's direction. This lets us save a few bytes because the IP will move in the same (horizontal) direction on both `w` and `k`.

The linearised code is this:

```
IY' *mRw..Y;m;.!z?~RZOk@

```

Let's go through it:

```
I       Read one line of input.
Y       Unzip. Separates the string into even and odd positions.
' *     Append a space to the odd half.
m       Truncate: discards characters from the longer of the two
        strings until they're the same length. So if the input
        length was even, appending a space will make the odd half
        longer and this discards the space again. Otherwise, the
        space just padded the odd half to the same length as the
        even half and this does nothing.
R       Reverse the odd half.
w       Push the current IP address to the return address stack.
        The purpose of this is to run the following section
        exactly twice.

          This first part splits the current line in half, based
          on an idea of Leo's:
  ..        Make two copies of the current half.
  Y         Unzip one of the copies. The actual strings are irrelevant
            but the important part is that the first string's length
            will be exactly half the original string's length (rounded up).
  ;         Discard the potentially shorter half.
  m         Truncate on the original string and its even half. This shortens
            the original string to the first half of its characters.
  ;         Discard the even half, because we only needed its length.
  .!        Store a copy of the first half on the tape.
  z         Drop. Use the first half to discard it from the original string.
            This gives us the the second (potentially shorter half).
  ?         Retrieve the first half from the tape.
  ~         Swap it so that the second half is on top.
          The string has now been split in half.
  R       Reverse the second half.
  Z       Zip. Interleave the two halves.
  O       Print the result with a trailing linefeed.

k       Pop an address from the return address stack and jump back there.
        The second time we reach this, the return address stack is empty,
        and this does nothing.
@       Terminate the program.

```
> 12 votes

# Answer
# Jelly, ~~23~~ 22 bytes

-1 byte thanks to Leo (bottom-left may be the padding)

```
LḂ⁶ẋ;µṚ,µm2œs2U0¦ż/µ€Y

```

A full program printing the result (the monadic link returns a list of lists of lists of characters).

**Try it online!** or see a test suite.

### How?

```
LḂ⁶ẋ;µṚ,µm2œs2U0¦ż/µ€Y - Main link: list of characters
L                      - length
 Ḃ                     - modulo 2
  ⁶                    - literal space character
   ẋ                   - repeat
    ;@                 - concatenate (swap @rguments) (appends a space if the input's length is odd)
      µ                - monadic chain separation, call that s
       Ṛ               - reverse s
        ,              - pair with s
         µ         µ€  - for €ach:
          m2           -   modulo 2 slice (take every other character)
            œs2        -   split into two "equal" chunks (first half longer if odd)
               U0¦     -   upend index 0 (reverse the second chunk)
                   /   -   reduce by:
                  ż    -     zip
                     Y - join with newlines (well just the one in this case)
                       - implicit print (mushes the sublists together)

```
> 4 votes

# Answer
## JavaScript (ES6), 104 bytes

```
f=
s=>s.replace(/./g,(c,i)=>a[1&~i][i+i>l?l-i:i]=c,a=[[` `],[]],l=s.length-1|1)&&a.map(a=>a.join``).join`
`
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

Works by emulating the execution path and filling the commands in as it goes.
> 1 votes

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


title: Find the Odd odds

text:
# Question
Title: Find the Odd odds
Given an unordered collection of positive integers by any reasonable input method, return all of the sub-collections that have an odd number of odd elements (i.e. have an odd total).

This is so you should aim to minimize the byte count of your program.

Since some languages only have ordered collections (lists, arrays, vectors, etc.) or don't have an unordered collection that allows duplicates, you may use ordered collections (regardless of your language choice), however you should not output any duplicate collections with different orders (e.g. `[2,3]` and `[3,2]`). You may output in whatever order you see fit.

## Test cases

```
[2,3,7,2] -> [[3],[7],[2,3],[2,7],[2,2,3],[2,2,7]]
[2,4,6,8] -> []
[4,9]     -> [[9],[4,9]]

```

# Answer
> 5 votes
# 05AB1E, 6 bytes

```
{æÙʒOÉ

```

Try it online!

```
{æÙʒOÉ
{      Sort
 æ     Powerset
  Ù    Uniqufy
   ʒ   Keep elements where
    O                      the sum
     É                             is uneven

```

-2 bytes thanks to @EriktheOutgolfer

# Answer
> 4 votes
# Python 3, 93 bytes

```
f=lambda x,r=[[]]:x and f(x[1:],r+[y+x[:1]for y in r])or{(*sorted(y),)for y in r if sum(y)&1}

```

Returns a set of tuples. Most likely way too long.

Try it online!

# Answer
> 3 votes
# Pyth, ~~10~~ ~~9~~ 8 bytes

```
{f%sT2yS

```

Try it online!

```
         # implicit input
       S # sort input, this way the subsets will already be sorted
      y  # all subsets
 f       # filter elements when ..
   sT    # the sum ..
  %  2   # is odd
{        # remove all duplicated elements
         # implicit output

```

# Answer
> 3 votes
# Python 2, 91 bytes

```
r=[[]]
for n in input():r+=map([n].__add__,r)
print{tuple(sorted(y))for y in r if sum(y)&1}

```

Prints a set of tuples. If a set of strings is allowed, `tuple(sorted(y))` can be replaced with ``sorted(y)`` for **86 bytes**.

Try it online!

# Answer
> 2 votes
# Jelly, 8 bytes

```
ṢŒPSḂ$ƇQ

```

Try it online!

Bug-fix thanks to Jonathan Allan.

-1 byte by using the alias for filter thanks to Riolku.

# Answer
> 2 votes
# Mathematica ~~31 44~~ 38 bytes

Among all subsets of the input set, it returns those for which the sum, `Tr`, is odd.

6 bytes saved thanks to alephalpha.

```
Select[Union@Subsets@Sort@#,OddQ@*Tr]&

```

---

```
 Select[Union@Subsets@Sort@#,OddQ@*Tr]&[{2,3,7,2}]

```

{{3}, {7}, {2, 3}, {2, 7}, {2, 2, 3}, {2, 2, 7}}

# Answer
> 2 votes
# Perl 6, 50 bytes

```
{.combinations.grep(*.sum!%%2).unique(:as(*.Bag))}

```

To filter out the same-up-to-ordering combinations I filter out duplicates by converting each to a `Bag` (unordered collection) before comparing. Unfortunately I couldn't find a way to accept a `Bag` as input that was as concise.

# Answer
> 2 votes
# Brachylog, 11 bytes

```
o⊇ᵘ{+ḃt1&}ˢ

```

Try it online!

I hoped to find a shorter solution, but here's the best I could do.

### Explanation

```
o⊇ᵘ{+ḃt1&}ˢ
o                                        the input, sorted
 ⊇ᵘ           Find all unique subsets of

   {    &}ˢ   Then select only those results where
    +                                          the sum
     ḃ                           the base 2 of
      t        The last digit of
       1                                               is 1.

```

Yeah, I could've used modulo 2 to check for oddness, but that's not an odd approach ;)

# Answer
> 1 votes
# PHP, 126 bytes

```
for(;++$i>>$argc<1;sort($t),$s&1?$r[join(_,$t)]=$t:0)for ($t=[],$j=$s=0;++$j<$argc;)$i>>$j&1?$s+=$t[]=$argv[$j]:0;print_r($r);

```

takes input from command line arguments; run with `-nr` or try it online.

**breakdown**

```
for(;++$i>>$argc<1;             # loop through subsets
    sort($t),                       # 2. sort subset
    $s&1?$r[join(_,$t)]=$t:0        # 3. if sum is odd, add subset to results
    )                               # 1. create subset:
    for ($t=[],$j=$s=0;++$j<$argc;)     # loop through elements
        $i>>$j&1?                       # if bit $j is set in $i
        $s+=$t[]=$argv[$j]:0;           # then add element to subset
print_r($r);                    # print results

```

---
Tags: code-golf, combinatorics
---


title: Fermat Near Misses

text:
# Question
Title: Fermat Near Misses
Fermat's last theorem says that there there are no positive, integral solutions to the equation `a^n + b^n = c^n` for any `n>2`. This was proven to be true by Andrew Wiles in 1994.

However, there are many "near misses" that almost satisfy the diophantine equation but miss it by one. Precisely, they are all the greater than 1 and are integral solutions of `a^3 + b^3 = c^3 + 1` (the sequence is the value of each side of the equation, in increasing order).

### Your task is given `n`, to print out the first `n` values of this sequence.

Here are the first few values of the sequence:

```
1729, 1092728, 3375001, 15438250, 121287376, 401947273, 3680797185, 6352182209, 7856862273, 12422690497, 73244501505, 145697644729, 179406144001, 648787169394, 938601300672, 985966166178, 1594232306569, 2898516861513, 9635042700640, 10119744747001, 31599452533376, 49108313528001, 50194406979073, 57507986235800, 58515008947768, 65753372717929, 71395901759126, 107741456072705, 194890060205353, 206173690790977, 251072400480057, 404682117722064, 498168062719418, 586607471154432, 588522607645609, 639746322022297, 729729243027001

```

This is , so shortest code in **bytes** wins!

# Answer
# Jelly, 16 bytes

```
*3‘
ḊŒc*3S€ċÇµ#Ç

```

Brute-force solution. Try it online!

```
*3‘           Helper link. Maps r to r³+1.

ḊŒc*3S€ċÇµ#Ç  Main link. No arguments.

         µ    Combine the links to the left into a chain.
          #   Read an integer n from STDIN and execute the chain to the left for
              k = 0, 1, 2, ... until n matches were found. Yield the matches.
Ḋ             Dequeue; yield [2, ..., k].
 Œc           Yield all 2-combinations of elements of that range.
   *3         Elevate the integers in each pair to the third power.
     S€       Compute the sum of each pair.
        Ç     Call the helper link, yielding k³+1.
       ċ      Count how many times k³+1 appears in the sums. This yields a truthy
              (i.e., non-zero) integer if and only if k is a match.
           Ç  Map the helper link over the array of matches.

```
> 14 votes

# Answer
# Perl, 78 bytes

```
#!perl -nl
grep$_<(($_+2)**(1/3)|0)**3,map$i**3-$_**3,2..$i++and$_-=print$i**3+1while$_

```

Brute force approach. Couting the shebang as two, input is taken from stdin.

**Sample Usage**

```
$ echo 10 | perl fermat-near-miss.pl
1729
1092728
3375001
15438250
121287376
401947273
3680797185
6352182209
7856862273
12422690497

```

Try it online!
> 8 votes

# Answer
# Brachylog, 31 bytes

```
:{#T#>>:{:3^}aLhH,Lb+.-H,#T=,}y

```

Try it online!

This is not complete brute force as this uses constraints. This is a bit slow on TIO (about 20 seconds for `N = 5`). Takes about 5 seconds for `N = 5` and 13 seconds for `N = 6` on my machine.

### Explanation

```
:{                           }y    Return the first Input outputs of that predicate
  #T                               #T is a built-in list of 3 variables
    #>                             #T must contain strictly positive values
      >                            #T must be a strictly decreasing list of integers
       :{:3^}aL                    L is the list of cubes of the integers in #T
              LhH,                 H is the first element of L (the biggest)
                  Lb+.             Output is the sum of the last two elements of L
                     .-H,          Output - 1 = H
                         #T=,      Find values for #T that satisfy those constaints

```
> 8 votes

# Answer
# Mathematica, 95 bytes

```
(b=9;While[Length[a=Select[Union@@Array[#^3+#2^3&,{b,b},2],IntegerQ[(#-1)^3^-1]&,#]]<#,b++];a)&

```

Unnamed function taking a single positive integer argument `#` and returning a list of the desired `#` integers. Spaced for human readability:

```
1  (b = 9; While[
2    Length[ a =
3      Select[
4        Union @@ Array[#^3 + #2^3 &, {b, b}, 2],
5        IntegerQ[(# - 1)^3^-1] &
6      , #]
7    ] < #, b++
8  ]; a) &

```

Line 4 calculates all possible sums of cubes of integers between 2 and `b`+1 (with the initialization `b=9` in line 1) in sorted order. Lines 3-5 select from those sums only those that are also one more than a perfect cube; line 6 limits that list to at most `#` values, which are stored in `a`. But if this list has in fact fewer than `#` values, the `While` loop in lines 1-7 increments `b` and tries again. Finally, line 8 outputs `a` once it's the right length.

Holy hell this version is slow! For one extra byte, we can change `b++` in line 7 to `b*=9` and make the code actually run in reasonable time (indeed, that's how I tested it).
> 7 votes

# Answer
## Racket 166 bytes

```
(let((c 0)(g(λ(x)(* x x x))))(for*((i(in-naturals))(j(range 1 i))(k(range j i))#:final(= c n))
(when(=(+(g j)(g k))(+ 1(g i)))(displayln(+ 1(g i)))(set! c(+ 1 c)))))

```

Ungolfed:

```
(define (f n)
  (let ((c 0)
        (g (λ (x) (* x x x))))
    (for* ((i (in-naturals))
           (j (range 1 i))
           (k (range j i))
           #:final (= c n))
      (when (= (+ (g j) (g k))
               (+ 1 (g i)))
        (displayln (+ 1(g i)))
        (set! c (add1 c))))))

```

Testing:

```
(f 5)

```

Output:

```
1729
1092728
3375001
15438250
121287376

```
> 6 votes

# Answer
# Python 2, ~~102~~ 98 bytes

```
def f(n,c=2):z=c**3+1;t=z in[(k/c)**3+(k%c)**3for k in range(c*c)];return[z]*n and[z]*t+f(n-t,c+1)

```

Try it online!
> 6 votes

# Answer
# Pari/GP, 107 bytes

```
F(n)=c=2;while(n>0,c++;C=c^3+1;a=2;b=c-1;while(a<b,K=a^3+b^3;if(K==C,print(C);n--;break);if(K>C, b--,a++)))

```

Finds the first 10 solutions in 10 sec.

Goal: ***a^3+b^3 = c^3+1***

1. Gets number of required solutions by function-argument ***n***
2. Increases ***c*** from ***3*** and for each ***c^3+1*** searches ***a*** and ***b*** with ***1 \< a \<= b \< c*** such that ***a^3+b^3=c^3+1*** . If found, decrease required number of further soulutions ***n*** by ***1*** and repeat
3. Finishes, when number of furtherly required solutions (in ***n***) equals ***0***

***Call it*** to get the first ten solutions:

```
F(10)

```

***Readable code*** (requires leading and trailing braces as indicators for block-notation of the function. Also for convenience prints all variables of a solution):

```
{F(m) = c=2;
   while(m>0,
     c++;C=c^3+1;
     a=2;b=c-1;
     while(a<b,
           K=a^3+b^3;
            if(K==C,print([a,b,c,C]);m--;break);
            if(K>C, b--,a++);
          );
    );}

```

# Pari/GP, 93 bytes

(Improvement by Dennis)

```
F(n)=c=2;while(n,C=c^3+1;a=2;b=c++;while(a<b,if(K=a^3+b^3-C,b-=K>0;a+=K<0,print(C);n--;b=a)))

```
> 5 votes

# Answer
# Python 2, ~~122~~ 119 Bytes

<sup>*why are you still upvoting? Dennis crushed this answer ;)*</sup>

Welcome to the longest solution to this question :/ I managed to shave off a whole byte by making longer conditions and removing as much indentation as possible.

```
x,y,z=2,3,4
n=input()
while n:
 if y**3+x**3-z**3==1and x<y<z:print z**3+1;n-=1
 x+=1
 if y<x:y+=1;x=2
 if z<y:z+=1;y=3

```

Output for `n = 5`:

```
1729
1092728
3375001
15438250
121287376

```
> 5 votes

# Answer
# TI-Basic, 90 bytes

There must be a shorter way...

```
Prompt N
2->X
3->Y
4->Z
While N
If 1=X³+Y³-Z³ and X<Y and Y<Z
Then
DS<(N,0
X+1->X
If Y<X
Then
2->X
Y+1->Y
End
If Z<Y
Then
3->Y
Z+1->Z
End
End

```
> 4 votes

# Answer
## MATLAB, 94 bytes

Another brute-force solution:

```
for z=4:inf,for y=3:z,for x=2:y,c=z^3+1;if x^3+y^3==c,n=n-1;c,if~n,return,end,end,end,end,end

```

Output for `n=4`:

```
>> n=4; fermat_near_misses
c =
        1729
c =
     1092728
c =
     3375001
c =
    15438250

```

Suppressing the `c=` part of the display increases the code to **100 bytes**

```
for z=4:inf,for y=3:z,for x=2:y,c=z^3+1;if x^3+y^3==c,n=n-1;disp(c),if~n,return,end,end,end,end,end

>> n=4; fermat_near_misses_cleandisp
        1729
     1092728
     3375001
    15438250

```
> 2 votes

# Answer
# C#, ~~188~~ ~~174~~ ~~187~~ 136 bytes

Golfed version thanks to TheLethalCoder for his great code golfing and tips (Try online!):

```
n=>{for(long a,b,c=3;n>0;c++)for(a=2;a<c;a++)for(b=a;b<c;b++)if(a*a*a+b*b*b==c*c*c+1)System.Console.WriteLine(c*c*(a=c)+n/n--);};

```

Execution time to find the first 10 numbers: 33,370842 seconds on my i7 laptop (original version below was 9,618127 seconds for the same task).

**Ungolfed version:**

```
using System;

public class Program
{
    public static void Main()
    {
        Action<int> action = n =>
        {
            for (long a, b, d, c = 3; n > 0; c++)
                for (a = 2; a < c; a++)
                    for (b = a; b < c; b++)
                        if (a * a * a + b * b * b == c * c * c + 1)
                            System.Console.WriteLine( c * c * (a = c) + n / n--);
        };

        //Called like
        action(5);
    }
}

```

Previous golfed 187 bytes version including `using System;`

```
using System;static void Main(){for(long a,b,c=3,n=int.Parse(Console.ReadLine());n>0;c++)for(a=2;a<c;a++)for(b=a;b<c;b++)if(a*a*a+b*b*b==c*c*c+1)Console.WriteLine(c*c*(a=c)+n/n--);}

```

Previous golfed 174 bytes version (thanks to Peter Taylor):

```
static void Main(){for(long a,b,c=3,n=int.Parse(Console.ReadLine());n>0;c++)for(a=2;a<c;a++)for(b=a;b<c;b++)if(a*a*a+b*b*b==c*c*c+1)Console.WriteLine(c*c*(a=c)+n/n--);}

```

Previous (original) golfed 188 bytes version (Try online!):

```
static void Main(){double a,b,c,d;int t=0,n=Convert.ToInt32(Console.ReadLine());for(c=3;t<n;c++)for(a=2;a<c;a++)for(b=a;b<c;b++){d=(c*c*c)+1;if(a*a*a+b*b*b==d){Console.WriteLine(d);t++;}}}

```

Execution time to find the first 10 numbers: 9,618127 seconds on my i7 laptop.

This is my first ever attempt in C# coding... A bit verbose compared to other languages...
> 2 votes

# Answer
# GameMaker Language, 119 bytes

Why is `show_message()` so long :(

```
x=2y=3z=4w=argument0 while n>0{if x*x*x+y*y*y-z*z*z=1&x<y&y<z{show_message(z*z*z+1)n--}x++if y<x{x=2y++}if z<y{y=3z++}}

```

x,y,z=2,3,4 n=input() while n: if y**3+x**3-z3==1and x3+1;n-=1 x+=1 if y
> 0 votes

# Answer
# Axiom, 246 bytes

```
h(x:PI):List INT==(r:List INT:=[];i:=0;a:=1;repeat(a:=a+1;b:=1;t:=a^3;repeat(b:=b+1;b>=a=>break;q:=t+b^3;l:=gcd(q-1,223092870);l~=1 and(q-1)rem(l^3)~=0=>0;c:=round((q-1)^(1./3))::INT;if c^3=q-1 then(r:=cons(q,r);i:=i+1;i>=x=>return reverse(r)))))

```

ungof and result

```
-- hh returns x in 1.. numbers in a INT list [y_1,...y_x] such that
-- for every y_k exist a,b,c in N with y_k=a^3+b^3=c^3+1
hh(x:PI):List INT==
   r:List INT:=[]
   i:=0;a:=1
   repeat
      a:=a+1
      b:=1
      t:=a^3
      repeat
          b:=b+1
          b>=a=>break
          q:=t+b^3
          l:=gcd(q-1,223092870);l~=1 and (q-1)rem(l^3)~=0 =>0 -- if l|(q-1)=> l^3|(q-1)
          c:=round((q-1.)^(1./3.))::INT
          if c^3=q-1 then(r:=cons(q,r);i:=i+1;output[i,a,b,c];i>=x=>return reverse(r))

(3) -> h 12
   (3)
   [1729, 1092728, 3375001, 15438250, 121287376, 401947273, 3680797185,
    6352182209, 7856862273, 12422690497, 73244501505, 145697644729]
                                                       Type: List Integer

```
> 0 votes

---
Tags: code-golf, math, sequence
---


title: Remind me again?

text:
# Question
Title: Remind me again?
# Introduction

Ever heard of Remind? No? Neither did I until about 2 years ago. Basic premise of it is for teachers to send out reminders and communicate with their students. Pretty neat, right? It even allows you send emotes and react to messages! Which I do on a daily basis.

But, one thing about Remind is that the teachers always send the "Do your homework!" "If you don't, you'll get an F!". But, there is useful stuff too, like "Test on Tuesday", or the occasional "Have a good day!". I almost always reply happy with a thumbs up, but sometimes, I have to put a thumbs down.

# Challenge

Your task today is to find out if a message has a certain connotation to it. If it has a positive connotation to it, reply with a thumbs up. If it has a negative connotation, reply with a thumbs down.

# How am I supposed to detect connotations?

A positive connotation will normally have 3 words in it. The 3 words are: **Happy, Good, and Passed**.

A negative connotation will have 3 also. Those 3: **Test, Fail, and Homework**.

# What am I testing for?

You are testing to see if a message contains positive, negative or **both** connotations.

If a message has positive connotations to it, go ahead and return the unicode *code point* for thumbs up (U+1F44D).

If it has negative connotations to it, return the unicode code point for thumbs down (U+1F44E).

If the message has both negative and positive connotations, return the code point for a neutral face (U+1F610).

If, for some other reason, it doesn't have either connotations, return a nice ol' shrug (¯\\\_(ツ)\_/¯). If the shrug doesn't show up right, here's the Emojipedia link to the shrug

# Constraints

* Program must take a message as input.
* Positive connotations must return thumbs up code point (U+1F44D)
* Negative connotations must return thumbs down code point (U+1F44E).
* If the message has both connotations, return the neutral face code point (U+1F610).
* If the message has neither connotations, return the shrug (¯\\\_(ツ)\_/¯).
* This is , Shortest bytes win

# Test cases.

```
Input -> Output
Happy Good Friday! -> U+1F44D
Congrats, you just played yourself -> ¯\_(ツ)_/¯
You failed the test. -> U+1F44E
Good job on the test. -> U+1F610

```

# Answer
> 2 votes
# Python 3, ~~182~~ ~~166~~ ~~159~~ 151 bytes

```
c=input().lower().count
print((["¯\_(ツ)_/¯"]+list(""))[any(map(c,["good","happy","passed"]))+any(map(c,["fail","test","homework"]))*2])

```

Try it online!

# Answer
> 0 votes
# JavaScript, UTF-8 encoded, 100 bytes

```
s=>['¯\_(ツ)_/¯',...''][2*/happy|good|passed/i.test(s)+/test|fail|homework/i.test(s)]

```

Test cases:

```
const a =
s=>['¯\_(ツ)_/¯',...''][2*/happy|good|passed/i.test(s)+/test|fail|homework/i.test(s)]

console.log(a('Happy Good Friday!'));
console.log(a('Congrats, you just played yourself'));
console.log(a('You failed the test.'));
console.log(a('Good job on the test.'));
```

# Answer
> 0 votes
## Powershell, 190 bytes

```
"$($s=Read-host;"$s ->";$1=("Test","Fail","Homework"|?{$s-match$_});$2=("Happy","Good","Passed"|?{$s-match$_});if($1-and$2){""}elseif($1){""}elseif($2){""}else{"¯\_(ツ)_/¯"})"

```

Displays the input and output next to eachother.

Happy Good Friday! -\>

Congrats, you just played yourself -\> ¯\\\_(ツ)\_/¯

You failed the test. -\>

Good job on the test. -\>

# Answer
> 0 votes
## PowerShell, 187 bytes

```
read-host|%{$s=$_;$f=0;0..5|?{$s.indexof((-split'Happy Good Passed Test Fail Homework')[$_],0,$s.length,3)+1}|%{$f=$f-bor(1,2)[$_/3]};$s+' -> '+('¯\_(ツ)_/¯','','','')[$f]}

```

---
Tags: code-golf, unicode
---


# Question
Title: Calculate the 3BV of a Minesweeper Board
The 3BV of a Minesweeper board represents the minimum number of left clicks required to solve the board if you already know the solution. It stands for "Bechtel's Board Benchmark Value". Here's his site explaining it.

Below is a solved Minesweeper board. The flags indicate mines; tiles without mines indicate the count of adjacent mines, including diagonally, except that tiles that should have "0" are left blank instead. The image shows which tiles need to be clicked in order to solve the board.

**Clicks counted towards the 3BV are:**

* **One for each flood-filled area** of blank tiles (zero mines adjacent) and their non-blank neighbors.
* **One for each other non-mine tile.**

---

### Another Example (3BV = 39)

---

Given a 2D array of values, `0` for clear and `1` for a mine (or a boolean), **return the 3BV**.

A board's dimensions will be at least 8x8, and at most 24x30, inclusive. Your program should handle all possible boards, not just the examples.

**Note: A board will never contain only mines.**

### Example I/O:

```
[[0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0],
[0,0,0,1,0,0,1,0],
[0,1,0,0,1,0,0,0],
[0,0,1,0,0,0,0,1],
[0,0,0,1,0,0,0,0],
[0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,1]]

23

[[0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0],
[0,0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0],
[0,1,0,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,1,0,0,0,1,0,1,0,1,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0],
[1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1],
[0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0],
[0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0,0,1,1,0,0],
[0,1,1,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0]]

187

```

# Answer
> 15 votes
# MATLAB, ~~92~~ ~~90~~ ~~86~~ ~~83~~ ~~79~~ ~~74~~ 72 bytes

```
x=input('');I=@(x)~imdilate(x,ones(3));[C,N]=bwlabel(I(x));nnz(I(C)-x)+N

```

This solution accepts the input in the form of a 2D matrix of 0's and 1's and will display the 3BV value for the provided input.

Here is slightly modified demo in Octave for those of you without MATLAB.

**Explanation**

The input matrix is dilated using a 3 x 3 matrix of `1`'s and then inverted (using `~`) which identifies all of the points that do not have mines as neighbors (`1`) or do (`0`). To determine the number of connected regions, we use `bwlabel` to label each connected region of `1`'s. The first output is the label matrix (`0` where the input was zero and any value in the range `1...N` where there was a `1` in the input where `N` is the index of the connected group that it belongs to). The second output is the number of regions (the number of clicks required to open them). The result of the `bwlabel` is shown in the image on the left.

We expand the first output of `bwlabel` using `imdilate` (all non-zeros are expanded) using a 3 x 3 matrix of `1`'s. The result is shown in the image in the middle.

To determine the remaining clicks, we then count the squares that are not in this expanded region (`~imdilate()`) and not a mine (`-x`) (white squares in the image on the right) and add this to the total number of open regions (the number of different colors in the image on the left) to get the 3BV.

# Answer
> 9 votes
# Octave, ~~86~~ ~~84~~ ~~79~~ 66 bytes

```
@(x)nnz(~imdilate(c=imerode(~x,o=ones(3)),o)-x)+max(bwlabel(c)(:))

```

This solution creates an anonymous function named `ans` which can then be passed a 2D matrix of `0`'s and `1`'s. The logic is the same as my MATLAB answer but uses a few tricks that Octave has to offer to save space.

This solution requires that the `image` package is installed.

**Demo here**

# Answer
> 2 votes
# MATL, ~~24~~ ~~22~~ 21 bytes

*1 byte saved thanks to @Luis*

```
4Y6Z+~l2#ZIw7MZ+G+~z+

```

Try it at MATL Online

**Explanation**

Again, this is similar to my MATLAB and Octave answers to this question.

```
        % Implicitly grab input array
4Y6     % Push the literal [1 1 1; 1 1 1; 1 1 1] to the stack
Z+      % Perform 2D convolution of the input with this array
~       % Negate the result
l2#ZI   % Call bwlabeln which dilates each open region and the second output
        % returns the number of open regions
w       % Flip the top two stack elements
7M      % Push the literal [1 1 1; 1 1 1; 1 1 1] to the stack again
Z+      % Perform 2D convolution
G+      % Explicitly grab the input and add it to the result
~z      % Count the number of 0's in the result (the remaining number of clicks)
+       % Add the total number of remaining clicks to the number of open regions

```

---
Tags: code-golf, game, minesweeper
---


# Question
Title: Tic Tac Toe: print all possible positions without duplicates
Write a program that outputs all possible Tic Tac Toe positions including the corresponding game outcome. Avoid duplicate output of equal positions.

The program takes no input.

### Rules:

* A position output must consist of 9 characters, using `X` and `O` for the taken squares, and an arbitrary non-whitespace character for the blank squares
* Each position must be printed in 3 lines/columns, with a blank line as a separator between two positions.
* Additional whitespace / blank lines / box drawing characters are welcome
* Player X goes first
* The *outcome* can be either of:

+ X has won
    + O has won
    + Draw
    + Game in progress

You are free to choose a suitable visualization of the position's outcome, e.g. as colored text, or as textual annotation, as long as it is placed near the corresponding position
* Positions are considered equal if one can be obtained from the other by rotation or mirroring. Duplicate positions must not be printed. (In other words, print the equality classes only.)
For example, print **only one** of the following:

```
X••  ••X  •••  •••
•••  •••  •••  •••
•••  •••  X••  ••X

```

---

### Sample output:

```
•••
•••
••• -

X••
•••
••• -

•X•
•••
••• -

•••
•X•
••• -

[…]

XXO
OOX
XXO /

OXO
XXX
OXO X

```

**Hint:** There are 765 positions, with 91 wins for X, 44 wins for O, and 3 draws.

---

A similar question has been asked before, but this one is different.

# Answer
# Jelly, ~~192~~ ~~179~~ 168 bytes

```
5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?
U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ
FSµ×’¬
ÑPµA_µọ9n1
,UŒDḢ$€;;ZS€f3,-3
Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ
Ça3Ŀa4Ŀ
3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶

```

Try it online! (Takes about 30 seconds, so be patient).

### How it Works

*High level overview:*

In intermediate steps, this stores X as `1`, unplaced as `0`, and O as `-1`. The program generates all 3^9 possibilities, then keeps only the valid positions based on meeting the three criteria:

* There is 1 or 0 more X than O.
* Not both X and O have won.
* If X has won, there is 1 more X than O. If O has won, there are an equal number of Os and Xs.

Then, the program replaces each game state with all of its rotations and reflections to get a list of all equivalence classes. This is the operation which takes most of the time.

The first game state is taken from each of the equivalence classes, then who won is calculated.

*Where this happens* The lines are numbered for readability

```
1: 5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?          ••calculates who wins (output as -1 or 1) or draw ("-") or in game ("/")
                 µ5ĿḢṠµ?          - if(someone won based on line 5):
   5ĿḢṠ                             - return 1 if X won and -1 if O won
       µ                          - else:
        Ff0L¬ị⁾-/                   - return "/" if the game is in progress and "-" if the game is at a tied end-state
2: U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ••outputs the equivalence class to a game state
   U,                             - list of game state [reflected horizontally, unaltered]
     µṚ,µ€                        - for each, replace with the list [reflected vertically,unaltered]
          µ“æɗþƑ’DịFs3,µ€€        - for each, replace with the list [rotated 90 degrees counter-clockwise,unaltered]
                          Fs9s3$€ - reformat into list of game states
                                 Ṣ- Sort
3: FSµ×’¬                         ••outputs truthy iff there is the right number of `X`s to `O`s (condition 1)
   FS                             - d = number of `X`s minus number of `O`s
     µ×’                          - d*(d-1): falsey iff d is 0 or 1
        ¬                         - logical not, to return truthy iff d is 0 or 1
4: ÑPµA_µọ9n1                     ••outputs truthy iff there is the right number of winners (condition 2)
   Ñ                              - the winners. [-3,3] is what we want to return falsy on
    PµA_µ                         - 18 on [-3,3] and 0 otherwise
         ọ9n1                     - not divisible by 9 exactly once: 0 on [-3,3] and 1 otherwise
5: ,UŒDḢ$€;;ZS€f3,-3              ••outputs the number of times each player won.
   ,UŒDḢ$€;;Z                     - the diagonals, rows, and columns of a board
             S€                   - sum of each. Returns -3 or 3 iff the line is only 1s or -1s
               f3,-3              - filter out, keeping only 3s and -3s
6: Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ             ••return truthy iff the winner corresponds to the respective numbers of X and O (condition 3)
   Ç,SS€                          - list of winners and how many more Xs than Os there are
             µSṠ‘µ?               - if O won, then
        µṪ                          - how many more Xs than Os there are
                                  - else:
          µṪC                       - the complement of how many more Xs than Os there are
                   ÷Ḣ             - deal with no one winning
7: Ça3Ŀa4Ŀ                        ••return truthy iff the game state meets all three conditions
   Ç 3Ŀ 4Ŀ                        - the three conditions: on line 3,4, and 6
    a  a                          - joined by logical ANDs
8: 3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶ ••do everything
   3ṗ9_2                        - all possible game states, with -1 for O and 1 for X
        s3$€                    - turn into two-dimensional game boards
            ÇÐf                 - filter based on line 6: if the board meets all three ocnditions
               2Ŀ€Q             - generate the equivalence classes for each and remove repeats based on line 1
                   Ḣ€           - get the first board from each class
                     µ;ÑFµ€     - append the winner to each board based on line 1
   µ3Ḷ’,“O¤X”yµ€                   - map each -1, 0, and 1 to the proper `O`,  `¤`, and `X`.
                Fs10µs3Gµ€         - format each board- winner combos
                          j⁾¶¶     - join the combos by double-newlines

```
> 6 votes

# Answer
# Python 2, ~~648~~ 620 bytes

```
import re
M=re.match
x='X';o='O'
R=lambda b,z=[6,3,0,7,4,1,8,5,2]:''.join(b[z[i]]for i in range(9))
p='XXX......|...XXX...|......XXX|X...X...X';q=p.replace(x,o)
def e(b):c=b.count;d=c(x)-c(o);w=M(p,b)or M(p,R(b));v=M(q,b)or M(q,R(b));return 0 if d not in[0,1]else 0 if w and v else(x if d==1 else 0)if w else(o if d==0 else 0)if v else'.'if'.'in b else'/'
h=set()
for n in range(3**9):
 b=reduce(lambda a,v:('.XO'[a[1]%3]+a[0],a[1]/3),range(9),('',n))[0]
 if b not in h:
	u=e(b)
	if u:print'%s\n%s\n%s %s\n'%(b[:3],b[3:6],b[6:],u)
	h.update(reduce(lambda a,v:a+[R(a[-2]),R(a[-1])],range(3),[b,R(b,[2,1,0,5,4,3,8,7,6])]))

```

Try it online!

Probably a bit of minor golfing possible here with this approach; but not a lot.

Edit: Thx to ovs, who noted a tweak gaining 28 bytes; and 3 from Artemis Fowl

**Un-golfed code**

The basic idea here is: brute force each of the 3^9=19683 possible board encodings. Keep track of the conjugates (rotations and reflections) of boards that have already been examined so you don't duplicate entries. At a minimum, valid boards must have either an equal number of X's and O's or else one more X than O. Not possible to have both a win for X and a win for O; plus some additional finicky constraints.

```
import re
from collections import Counter

FLIP_XFRM = [2,1,0,5,4,3,8,7,6]
ROT_XFRM = [6,3,0,7,4,1,8,5,2]

def xfrm(b, xf):
    return ''.join(b[xf[i]] for i in range(9))

def flipIt(b):
    return xfrm(b,FLIP_XFRM)

def rotIt(b):
    return xfrm(b,ROT_XFRM)

def conjugates(b):
    conj = [b, flipIt(b)]
    for i in range(3):
        conj += [rotIt(conj[-2]), rotIt(conj[-1])]
    return conj

def tttToB(n):
    b = ''
    for i in range(9):
        b = '.XO'[n %3]+b
        n /= 3
    return b

def printBoard(b,outcome='.'):
    print '%s\n%s\n%s %s\n' % (b[:3],b[3:6],b[6:],outcome)

def evalBoard(b):
    c = Counter(b)
    if c['X']-c['O'] not in [0,1]:
        return False

    p1 = 'XXX......|...XXX...|......XXX|X...X...X'
    p2 = p1.replace('X','O')

    br = rotIt(b)
    w1 = re.match(p1,b) or re.match(p1,br)
    w2 = re.match(p2,b) or re.match(p2,br)
    if w1 and w2:
        return False

    if w1:
        return 'X' if c['X']==c['O']+1 else False

    if w2:
        return 'O' if c['X']==c['O'] else False

    if '.' in b:
        return '.'
    else:
        return '/'

def main():
    history = set()
    for m in range(3**9):
        b = tttToB(m)
        if b not in history:
            outcome = evalBoard(b)
            if outcome:
                printBoard(b,outcome)
            history.update(conjugates(b))

main()

```
> 2 votes

# Answer
# Ruby, 305 bytes

```
19683.times{|i|c=(i%3).to_s
s=(9**8+i/3*6562).to_s(3)
w=0
t=(0..3).map{|j|r=s[1+j*2,9]
w|=1<<r[0..2].sum%8|1<<(c+r[j/2]+r[4+j/2]).sum%8
[r,r.reverse].min}.min
v=t[0..2]+$/+t[7]+c+t[3]+$/+t[6]+t[5]+t[4]
w&=65
b=v.sum%51
w<65&&b>w/64&&b<3-w%2&&t==s[1,9]&&puts(v.tr("012","X.O"),w<1?v.include?(?1):w%31,"")}

```

This works similiarly to the other answers in that it generates all `3**9` boards then filters out the valid ones. Internally, we use ternary numbers where `0=X 1=. 2=O` in the output. Iterate `c` through the 3 possible values for the centre, and `s` through the `3**8 = 6561` values for the perimeter. Before converting `i/3` to a string representation of a ternary number, we multiply by `6562` to duplicate all digits, and add `3**16` to start the number with a 1, in order to ensure there are leading zeros where applicable. `w` is the win condition - set this to zero.

For each board **Iterate through 4 rotations** of the digits in `s` to find the lexically lowest version of the current 8 digit ternary number representing the perimeter. At the same time, add the ascii values of the first 3 digits (top row of current rotation) and use this to check for a win. Also, add the ascii values of `c` and a pair of diametrically opposite digits to check if there is a win through the centre.

**Check if the output is valid** \- If both 1's bit and 64's bit of `w` are both set, both sides win - this is not valid. Check the balance of X's and O's (if there is no winner yet it can be either equal X and O or one more X - but if the game is won, there is only one possible value, as the winner must have gone last.) To avoid showing different rotations of the same board, only output if the lexically lowest version of the perimeter corresponds to the current value of `s[2,9]`.

**Output the board**, sustituting the symbols `tr("012","X.O")`. The game status is shown below the board. If w=0, this is `true` if there are still empty squares (game still in progress) and `false` if the board is full. If `w` is nonzero we output `1` if player 1 (X) has won or `64%31==2` if player 2 (O) has won.

**Ungolfed**

```
19683.times{|i|                             #check 3**9 possibilities
  c=(i%3).to_s                              #centre square: 0=X, 1=. 2=O
  s=(9**8+i/3*6562).to_s(3)                 #perimeter:multiply i/3 by 3**8+1 to duplicate digits, add 3**16 to give a 1 at left side to ensure leading zeros
  w=0                                       #set w=0 to clear wins (1´s bit holds win for X, 64´s bit holds win for O)
  t=(0..3).map{|j|                          #build an array of 4 different rotations of the perimeter
     r=s[1+j*2,9]                           #by taking different 9-character slices of s
     w|=1<<r[0..2].sum%8|                   #add ascii codes mod 8 for top row of current rotation, take sum modulo 8 to give sum of digits. set a bit in w (we only care about bits 0 and 6)
        1<<(c+r[j/2]+r[4+j/2]).sum%8        #do the same for one of the 4 lines through the centre. if j/2=0 check diagonal, if j/2=1 check horizontal/vertical.
     [r,r.reverse].min}.min                 #add to the array the lexically lowest version(forward or reverse) of the current rotation. When the loop ends, find the lexically lowest version overall and assign to t.
  v=t[0..2]+$/+t[7]+c+t[3]+$/+t[6]+t[5]+t[4]#format the output into a square 012\n 7c3\n 654
  w&=65                                     #clear bits 1 through 5 of w, leave only bits 0 and 6 which are the ones of interest.
  b=v.sum%51                                #valid values of sum of ascii codes in output are 461 (equal 0's and 2's) and 460 (one more 0 than 2). Take modulo 51 to reduce these values to 1 and 2
  w<65&&                                    #if a maximum of one player has a winning line (not both) and
  b>w/64&&                                  #b must be 1 or 2 (only 2 permitted if O's won)
  b<3-w%2&&                                 #b must be 1 or 2 (only 1 permitted if X's won)
  t==s[1,9]&&                               #s[2,9] is the lexically lowest version of the current board (to avoid duplicates) then
  puts(v.tr("012","X.O"),                   #output the board, subsituting internal "012" characters for external "X.O"
  w<1?v.include?(?1):w%31,"")               #if nobody won, output true if game in still in play (1's present on board) else false
}                                           #if there is a winner, output (player) 1 for X, (player) w%31=2 for O. Also output a blank line.

```

**Checking scheme**

The diagrams below show the scheme for rotation (and win checking, in capitals). The diagrams are shown unrotated. The four different rotations are taken as substrings from the double copy of `i/3`, with the 3 consecutive capital letters on the perimeter of each diagram (the "top" per current rotation) being the first 3 characters in the 9-character substring. For each rotation, 9-character reversal (diagonal flip about A-E or C-G axis) is also tried. The board is only output if the current value of `i/3` is the lexically lowest of all rotations and mirrors.

```
 ABC    abC    aBc    Abc
 hZd    hZD    hZd    HZD
 gfE    GfE    GFE    Gfe

```
> 2 votes

---
Tags: code-golf, tic-tac-toe
---


# Question
Title: Oneliner to merge lines with same first field
*This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.*

I have a file with this format:

```
a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line

```

The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.

Desired output:

```
a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line

```

I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.

Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.

(I run on MacOS, so I am personally most interested in implementations that run on the mac).

---

Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).

Input:

```
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom

```

Desired output:

```
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom

```

# Answer
> 7 votes
# Retina, 17 bytes

* 12 bytes saved thanks to @MartinEnder
* 1 byte saved thanks to @jimmy23013

Scored in ISO 8859-1 encoded bytes.

Uses `;` instead of `|` as the input field separator.

```
(?<=(.+;).+)¶\1
%

```

Try it online.

# Answer
> 5 votes
# , ~~16~~ 13 bytes

```
òí^¨á«©.*úsî±

```

Try it online!

You said

> Feel free to change the delimiter

So I picked `|` as the delimiter. If this is invalid, let me know and I'll change it.

Explanation:

```
ò                #Recursively:
 í               #Search for the following on any line:
  ^¨á«©          #1 or more alphabetic characters at the beginning of the line
       .*        #Followed by anything
         ús      #Mark everything after this to be removed:
           î±    #A new line, then the first match again (one or more alphabetic characters)

```

# Answer
> 3 votes
# SQL (PostgreSQL), ~~43~~ 72 bytes

```
COPY T FROM'T'(DELIMITER'|');SELECT a,string_agg(b,'%')FROM T GROUP BY A

```

This takes advantage of the handy string\_agg aggregate function in PostgreSQL. Input is from a table called `T` with 2 columns `A` and `B`. To comply with the question better I have included to command to load data from a file into the table. The file is `T` as well. I haven't counted the table create statement.
The output will be unordered, but if that is a problem it can be fixed with an `ORDER BY A`

SQLFiddle didn't want to play for me, but this is what I get in my setup.

```
CREATE TABLE T (A VARCHAR(9),B VARCHAR(30));

COPY T FROM'T'(DELIMITER'|');SELECT a,string_agg(b,'%')FROM T GROUP BY A
a   string_agg
--- ----------------------------------------
c   rest of fourth line
b   rest of second line%rest of third line
a   rest of first line
d   rest of fifth line%rest of sixth line

```

# Answer
> 3 votes
# Perl `-0n`, 2 + 43 = 45 bytes

```
s/
.*\|/%/g,print for/(.*\|)((?:
\1|.)*
)/g

```

Demo:

```
$ perl -0ne 's/
> .*\|/%/g,print for/(.*\|)((?:
> \1|.)*
> )/g' <<EOF
> why|[may express] surprise, reluctance, impatience, annoyance, indignation
> whom|[used in] questions, subordination
> whom|[possessive] whose
> whom|[subjective] who
> whoever|[objective] whomever
> whoever|[possessive] whosever
> who|[possessive] whose
> who|[objective] whom
> EOF
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom

```

# Answer
> 2 votes
# C, 127 bytes

```
o[99],n[99],p=n;main(i){for(;gets(n);strncmp(o,n,i-p)?printf(*o?"\n%s":"%s",n),strcpy(o,n):printf(" /%s",i))i=1+strchr(n,'|');}

```

Works with gcc. Changed delimiter to `/`. Takes input from stdin and writes output to stdout, so call with input redirection `./a.out <filename`

Ungolfed:

```
o[99],n[99] //declare int, to save two bytes for the bounds
,p=n; //p is an int, saves one byte as opposed to applying an (int) cast to n,
//or to declaring o and n as char arrays
main(i){for(;gets(n);strncmp(o,n,i-p //an (int)n cast would be needed;
// -(n-i) does not work either,
//because pointer arithmetics scales to (int*)
)?printf(*o?"\n%s":"%s" //to avoid a newline at the beginning of output
,n),strcpy(o,n):printf(" /%s",i))i=1+strchr(n,'|');}

```

# Answer
> 1 votes
# Pyth - 15 bytes

Making a few assumptions about the problem, will change when OP clarifies.

```
jm+Khhd-sdK.ghk

```

Try it online here.

# Answer
> 1 votes
# Python 3 - 146 Bytes

Input is the filename or file path of the file, output is to stdout. Could be a lot shorter if I could take input as raw text from command line

Takes input from stdin and outputs to stdin. Setup with separator `"|"`. To test the first example input use the separator `" | "`

```
from itertools import*
for c,b in groupby([x.split("|")for x in input().split("\n")],key=lambda x:x[0]):print(c,"|"," % ".join((a[1]for a in b)))

```

# Answer
> 1 votes
# Java 7, 167 bytes

It can probably be golfed more by using a different approach..

```
import java.util.*;Map c(String[]a){Map m=new HashMap();for(String s:a){String[]x=s.split("=");Object l;m.put(x[0],(l=m.get(x[0]))!=null?l+"%"+x[1]:x[1]);}return m;}

```

*NOTE:* The method above creates and returns a `HashMap` with the desired key-value pairs. However, it doesn't print it in the exact output as in OP's question with `|` as output-delimiter between the keys and new values. Judging by *MickeyT's SQL answer* where he returned a database table I figured this is allowed; if not more bytes should be added for a print function.

**Ungolfed & test code:**

```
import java.util.*;

class Main{

    static Map c(String[] a){
        Map m = new HashMap();
        for(String s : a){
            String[] x = s.split("\\|");
            Object l;
            m.put(x[0], (l = m.get(x[0])) != null
                            ? l + "%" + x[1]
                            : x[1]);
        }
        return m;
    }

    public static void main(String[] a){
        Map m = c(new String[]{
            "why|[may express] surprise, reluctance, impatience, annoyance, indignation",
            "whom|[used in] questions, subordination",
            "whom|[possessive] whose",
            "whom|[subjective] who",
            "whoever|[objective] whomever",
            "whoever|[possessive] whosever",
            "who|[possessive] whose",
            "who|[objective] whom"
        });

        // Object instead of Map.EntrySet because the method returns a generic Map
        for (Object e : m.entrySet()){
            System.out.println(e.toString().replace("=", "|"));
        }
    }
}

```

**Output:**

```
whoever|[objective] whomever%[possessive] whosever
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
why|[may express] surprise, reluctance, impatience, annoyance, indignation
who|[possessive] whose%[objective] whom

```

# Answer
> 1 votes
### PowerShell, 85 bytes

Strings are merged using hashtable:

```
%{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}

```

### Example

Since PowerShell doesn't support stdin redirection via `<`, I'm assuming that `Get-Content .\Filename.txt |` will be used as default I/O method.

```
Get-Content .\Filename.txt | %{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}

```

### Output

```
whoever|[objective] whomever%[possessive] whosever
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
who|[possessive] whose%[objective] whom

```

# Answer
> 1 votes
## APL, 42 chars

```
{⊃{∊⍺,{⍺'%'⍵}/⍵}⌸/↓[1]↑{(1,¯1↓'|'=⍵)⊂⍵}¨⍵}

```

# Answer
> 0 votes
# Sed, 55 bytes

```
:a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb

```

---

Test run :

```
$ echo """why|[may express] surprise, reluctance, impatience, annoyance, indignation
> whom|[used in] questions, subordination
> whom|[possessive] whose
> whom|[subjective] who
> whoever|[objective] whomever
> whoever|[possessive] whosever
> who|[possessive] whose
> who|[objective] whom""" | sed ':a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb'
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination %[possessive] whose %[subjective] who
whoever|[objective] whomever %[possessive] whosever
who|[possessive] whose %[objective] whom

```

# Answer
> 0 votes
# q/kdb+, 46 bytes

**Solution:**

```
exec"%"sv v by k from flip`k`v!("s*";"|")0:`:f

```

**Example:**

```
q)exec"%"sv v by k from flip`k`v!("s*";"|")0:`:f
who    | "[possessive] whose%[objective] whom"
whoever| "[objective] whomever%[possessive] whosever"
whom   | "[used in] questions, subordination%[possessive] whose%[subjective] who"
why    | "[may express] surprise, reluctance, impatience, annoyance, indignation"

```

**Explanation:**

```
`:f            // assumes the file is named 'f'
("s*";"|")0:   // read in file, assume it has two columns delimitered by pipe
flip `k`v      // convert into table with columns k (key) and v (value)
exec .. by k   // group on key
"%"sv v        // join values with "%"

```

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


title: Plot the Gaussian Distribution in 3D

text:
# Question
Title: Plot the Gaussian Distribution in 3D
> In probability theory, the normal (or Gaussian) distribution is a very common continuous probability distribution. Normal distributions are important in statistics and are often used in the natural and social sciences to represent real-valued random variables whose distributions are not known.

## The challenge

Your challenge is to plot the probability density of the Gaussian Distribution on a 3-dimensional plane. This function is defined as:

Where:

**A** = 1, **σx** = **σy** = **σ**

## Rules

* Your program must take one input **σ**, the standard deviation.
* Your program must print a 3D plot of the Gaussian Distribution in the highest quality as your language/system allows.
* Your program may not use a direct Gaussian Distribution or probability density builtin.
* Your program does not have to terminate.
* Your plot may be in black and white or color.
* Your plot must have grid lines on the bottom. Grid lines on the sides (as shown in the examples) are unnecessary.
* Your plot does not need to have line numbers next to the grid lines.

## Scoring

As usual in , the submission with the least bytes wins! I may never "accept" an answer using the button, unless one is incredibly small and intuitive.

## Example output

Your output could look something like this:

Or it could look like this:

More valid outputs. Invalid outputs.

# Answer
> 7 votes
# Gnuplot 4, ~~64~~ ~~62~~ ~~61~~ ~~60~~ 47 bytes

*(Tied with Mathematica! WooHoo!)*

```
se t pn;se is 80;sp exp(-(x**2+y**2)/(2*$0**2))

```

Save the above code into a file named `A.gp` and invoke it with the following:

`gnuplot -e 'call "A.gp" $1'>GnuPlot3D.png`

where the `$1` is to be replaced with the value of `σ`. This will save a `.png` file named `GnuPlot3D.png` containing the desired output into the current working directory.

Note that this *only* works with distributions of Gnuplot 4 since in Gnuplot 5 the `$n` references to arguments were deprecated and replaced with the unfortunately more verbose `ARGn`.

**Sample output with `σ = 3`:**

This output is fine according to OP.

---

# Gnuplot 4, Alternate Solution, 60 bytes

Here is an alternate solution which is much longer than the previous one but the output looks much better in my opinion.

```
se t pn;se is 80;se xyp 0;sp exp(-(x**2+y**2)/(2*$0**2))w pm

```

This still requires Gnuplot 4 for the same reason as the previous solution.

**Sample output with `σ = 3`:**

# Answer
> 16 votes
# C++, ~~3477~~ 3344 bytes

Byte count does not include the unnecessary newlines.
MD XF golfed off 133 bytes.

There's no way C++ can compete for this, but I thought it would be fun to write a software renderer for the challenge. I tore out and golfed some chunks of GLM for the 3D math and used Xiaolin Wu's line algorithm for rasterization. The program outputs the result to a PGM file named `g`.

```
#include<array>
#include<cmath>
#include<vector>
#include<string>
#include<fstream>
#include<algorithm>
#include<functional>
#define L for
#define A auto
#define E swap
#define F float
#define U using
U namespace std;
#define K vector
#define N <<"\n"
#define Z size_t
#define R return
#define B uint8_t
#define I uint32_t
#define P operator
#define W(V)<<V<<' '
#define Y template<Z C>
#define G(O)Y vc<C>P O(vc<C>v,F s){vc<C>o;L(Z i=0;i<C;++i){o\
[i]=v[i]O s;}R o;}Y vc<C>P O(vc<C>l, vc<C>r){vc<C>o;L(Z i=0;i<C;++i){o[i]=l[i]O r[i];}R o;}
Y U vc=array<F,C>;U v2=vc<2>;U v3=vc<3>;U v4=vc<4>;U m4=array<v4,4>;G(+)G(-)G(*)G(/)Y F d(
vc<C>a,vc<C>b){F o=0;L(Z i=0;i<C;++i){o+=a[i]*b[i];}R o;}Y vc<C>n(vc<C>v){R v/sqrt(d(v,v));
}v3 cr(v3 a,v3 b){R v3{a[1]*b[2]-b[1]*a[2],a[2]*b[0]-b[2]*a[0],a[0]*b[1]-b[0]*a[1]};}m4 P*(
m4 l,m4 r){R{l[0]*r[0][0]+l[1]*r[0][1]+l[2]*r[0][2]+l[3]*r[0][3],l[0]*r[1][0]+l[1]*r[1][1]+
l[2]*r[1][2]+l[3]*r[1][3],l[0]*r[2][0]+l[1]*r[2][1]+l[2]*r[2][2]+l[3]*r[2][3],l[0]*r[3][0]+
l[1]*r[3][1]+l[2]*r[3][2]+l[3]*r[3][3]};}v4 P*(m4 m,v4 v){R v4{m[0][0]*v[0]+m[1][0]*v[1]+m[
2][0]*v[2]+m[3][0]*v[3],m[0][1]*v[0]+m[1][1]*v[1]+m[2][1]*v[2]+m[3][1]*v[3],m[0][2]*v[0]+m[
1][2]*v[1]+m[2][2]*v[2]+m[3][2]*v[3],m[0][3]*v[0]+m[1][3]*v[1]+m[2][3]*v[2]+m[3][3]*v[3]};}
m4 at(v3 a,v3 b,v3 c){A f=n(b-a);A s=n(cr(f,c));A u=cr(s,f);A o=m4{1,0,0,0,0,1,0,0,0,0,1,0,
0,0,0,1};o[0][0]=s[0];o[1][0]=s[1];o[2][0]=s[2];o[0][1]=u[0];o[1][1]=u[1];o[2][1]=u[2];o[0]
[2]=-f[0];o[1][2]=-f[1];o[2][2]=-f[2];o[3][0]=-d(s,a);o[3][1]=-d(u,a);o[3][2]=d(f,a);R o;}
m4 pr(F f,F a,F b,F c){F t=tan(f*.5f);m4 o{};o[0][0]=1.f/(t*a);o[1][1]=1.f/t;o[2][3]=-1;o[2
][2]=c/(b-c);o[3][2]=-(c*b)/(c-b);R o;}F lr(F a,F b,F t){R fma(t,b,fma(-t,a,a));}F fp(F f){
R f<0?1-(f-floor(f)):f-floor(f);}F rf(F f){R 1-fp(f);}struct S{I w,h; K<F> f;S(I w,I h):w{w
},h{h},f(w*h){}F&P[](pair<I,I>c){static F z;z=0;Z i=c.first*w+c.second;R i<f.size()?f[i]:z;
}F*b(){R f.data();}Y vc<C>n(vc<C>v){v[0]=lr((F)w*.5f,(F)w,v[0]);v[1]=lr((F)h*.5f,(F)h,-v[1]
);R v;}};I xe(S&f,v2 v,bool s,F g,F c,F*q=0){I p=(I)round(v[0]);A ye=v[1]+g*(p-v[0]);A xd=
rf(v[0]+.5f);A x=p;A y=(I)ye;(s?f[{y,x}]:f[{x,y}])+=(rf(ye)*xd)*c;(s?f[{y+1,x}]:f[{x,y+1}])
+=(fp(ye)*xd)*c;if(q){*q=ye+g;}R x;}K<v4> g(F i,I r,function<v4(F,F)>f){K<v4>g;F p=i*.5f;F
q=1.f/r;L(Z zi=0;zi<r;++zi){F z=lr(-p,p,zi*q);L(Z h=0;h<r;++h){F x=lr(-p,p,h*q);g.push_back
(f(x,z));}}R g;}B xw(S&f,v2 b,v2 e,F c){E(b[0],b[1]);E(e[0],e[1]);A s=abs(e[1]-b[1])>abs
(e[0]-b[0]);if(s){E(b[0],b[1]);E(e[0],e[1]);}if(b[0]>e[0]){E(b[0],e[0]);E(b[1],e[1]);}F yi=
0;A d=e-b;A g=d[0]?d[1]/d[0]:1;A xB=xe(f,b,s,g,c,&yi);A xE=xe(f,e,s,g,c);L(I x=xB+1;x<xE;++
x){(s?f[{(I)yi,x}]:f[{x,(I)yi}])+=rf(yi)*c;(s?f[{(I)yi+1,x}]:f[{x,(I)yi+1}])+=fp(yi)*c;yi+=
g;}}v4 tp(S&s,m4 m,v4 v){v=m*v;R s.n(v/v[3]);}main(){F l=6;Z c=64;A J=g(l,c,[](F x,F z){R
v4{x,exp(-(pow(x,2)+pow(z,2))/(2*pow(0.75f,2))),z,1};});I w=1024;I h=w;S s(w,h);m4 m=pr(
1.0472f,(F)w/(F)h,3.5f,11.4f)*at({4.8f,3,4.8f},{0,0,0},{0,1,0});L(Z j=0;j<c;++j){L(Z i=0;i<
c;++i){Z id=j*c+i;A p=tp(s,m,J[id]);A dp=[&](Z o){A e=tp(s,m,J[id+o]);F v=(p[2]+e[2])*0.5f;
xw(s,{p[0],p[1]},{e[0],e[1]},1.f-v);};if(i<c-1){dp(1);}if(j<c-1){dp(c);}}}K<B> b(w*h);L(Z i
=0;i<b.size();++i){b[i]=(B)round((1-min(max(s.b()[i],0.f),1.f))*255);}ofstream f("g");f
W("P2")N;f W(w)W(h)N;f W(255)N;L(I y=0;y<h;++y){L(I x=0;x<w;++x)f W((I)b[y*w+x]);f N;}R 0;}

```
* `l` is the length of one side of the grid in world space.
* `c` is the number of vertices along each edge of the grid.
* The function that creates the grid is called with a function that takes two inputs, the `x` and `z` (+y goes up) world space coordinates of the vertex, and returns the world space position of the vertex.
* `w` is the width of the pgm
* `h` is the height of the pgm
* `m` is the view/projection matrix. The arguments used to create `m` are...
    + field of view in radians
    + aspect ratio of the pgm
    + near clip plane
    + far clip plane
    + camera position
    + camera target
    + up vector

The renderer could easily have more features, better performance, and be better golfed, but I've had my fun!

# Answer
> 10 votes
# Mathematica, 47 bytes

```
Plot3D[E^(-(x^2+y^2)/2/#^2),{x,-6,6},{y,-6,6}]&

```

takes as input σ

**Input**

> \[2\]

**output**

*-2 bytes thanks to LLlAMnYP*

# Answer
> 7 votes
# R, ~~105~~ ~~102~~ ~~87~~ 86 bytes

```
s=scan();plot3D::persp3D(z=sapply(x<-seq(-6,6,.1),function(y)exp(-(y^2+x^2)/(2*s^2))))

```

Takes Sigma from STDIN. Creates a vector from `-6` to `6` in steps of `.1` for both `x` and `y`, ~~then creates an `121x121` matrix by taking the outer product of `x` and `y`. This is shorter than calling `matrix` and specifying the dimensions. The matrix is now already filled, but that's ok, because we are overwriting that.~~

~~The `for`-loop loops over the values in `x`, making use of the vectorized operations in `R`, creating the density matrix one row at a time.~~

`(s)apply` again is a shorter method for vectorized operations. Like the hero it is, it handles the creation of the matrix all by itself, saving quite a few bytes.

## ~~128~~ ~~125~~ ~~110~~ 109 bytes, but way more fancy:

This plot is created by the `plotly` package. Sadly the specification is a bit wordy, so this costs a lot of bytes. The result is really really fancy though. I would highly recommend trying it out for yourself.

```
s=scan();plotly::plot_ly(z=sapply(x<-seq(-6,6,.1),function(y)exp(-(y^2+x^2)/(2*s^2))),x=x,y=x,type="surface")

```

# Answer
> 6 votes
# Applesoft BASIC, ~~930~~ ~~783~~ ~~782~~ ~~727~~ ~~719~~ ~~702~~ ~~695~~ 637 bytes

-72 bytes and a working program thanks to ceilingcat spotting my error and a shortened algorithm

```
0TEXT:HOME:INPUTN:HGR:HCOLOR=3:W=279:H=159:L=W-100:Z=L/10:B=H-100:C=H-60:K=0.5:M=1/(2*3.14159265*N*N):FORI=0TO10STEPK:X=10*I+1:Y=10*I+B:HPLOTX,Y:FORJ=0TOL STEP1:O=10*J/L:D=ABS(5-I):E=ABS(5-O):R=(D*D+E*E)/(2*N*N):G=EXP(-R)*M:A=INT((C*G)/M):X=10*I+Z*O+1:Y=10*I+B-A:HPLOTTOX,Y:IF(I=0)GOTO4
1IF(J=L)GOTO3
2V=INT(J/10):IF((J/10)<>V)GOTO5
3D=ABS(5-I+K):E=ABS(5-O):R=(D*D+E*E)/(2*N*N):U=EXP(-R)/(2*3.14159*N*N):S=INT((C*U)/M):P=10*(I-K)+Z*O+1:Q=10*(I-K)+B-S:HPLOT TOP,Q:HPLOTX,Y
4IF(J=0)GOTO7:IF(I<10)GOTO5:IF(J=L)GOTO6:V=INT(J/10):IF((J/10)=V)GOTO6
5HCOLOR=0
6HPLOTTOX,10*I+B:HCOLOR=3:HPLOTX,Y
7NEXTJ:NEXTI:HPLOTW+1,H:HPLOTTO101,H:HPLOTTO0+1,H

```

Ungolfed version here.

When given input `1`:

When given input `2`:

---
Tags: code-golf, math, graphical-output, probability-theory
---