# Question
Title: Golf a bijection \$\mathbb{N}^n\to\mathbb{N}\$
Your task is to write a program which implements a bijection \\$\mathbb{N}^n\to\mathbb{N}\\$ for \\$n \ge 1\\$. Your program should take \\$n\\$ natural numbers as input, in any acceptable method (including taking them as a single, \\$n\\$ element list/array) and output a unique natural number for all possible inputs.

In layman's terms, a **bijection** \\$\mathbb{N}^n\to\mathbb{N}\\$ means:

* Take \\$n\\$ natural numbers as input
* Map these \\$n\\$ natural numbers to a single natural number output
* For every possible input, the output is provably unique
* For every possible output, there exists an input which will give that output

For example, the Cantor pairing function \\$\pi : \mathbb{N}^2\to\mathbb{N}\\$ is a bijection that takes two natural numbers and maps each pair to a unique natural number.

You may implement whatever bijective function you wish, so long as it is proven to be bijective for all possible inputs. Please include this proof (either directly or through a link) in your answer. This is so the shortest code, in bytes, wins.

You may decide whether you'd like to use \\$\mathbb{N} = \\{1, 2, 3, \dots\\}\\$ or \\$\mathbb{N} = \\{0, 1, 2, \dots\\}\\$, so long as this is consistent for all \\$n\\$.

# Answer
# APL (Dyalog Unicode), ~~13~~ 10 bytes

```
(⊢+1⊥∘⍳+)/

```

Try it online!

Similar to other answers, since the Cantor pairing is bijective, compositing \\$n-1\\$ Cantor pairings is bijective as well.

```
(       )/  ⍝ reduce the input with following function
       +    ⍝ left argument + right argument
      ⍳     ⍝ the first left+right positive integers
   1⊥       ⍝ convert those from base 1 (sum)
 ⊢+         ⍝ + right argument

```
> 6 votes

# Answer
# , 8 bytes

```
,@|:&.#:

```

Try it online! (outputs the 10x10 matrix for f(A,B) and some consecutive numbers for n=3.)

Basically uses Neil's initial idea, interweaving the bits by evenly distributing them (so for n=3, the bit mask for the output is `… 1 2 3 1 2 3 1 2 3`.). But instead of shifting the bits, we make use of shapes: Convert each number into base 2 and pad lists with zeros, f.e. `#: 2 3 8` is

```
0 0 1 0
0 0 1 1
1 0 0 0

```

Transpose the matrix with `|:`:

```
0 0 1
0 0 0
1 1 0
0 1 0

```

And 'deshape' with `,`, i.e. join the rows into a list: `0 0 1 0 0 0 1 1 0 0 1 0` and convert it back from base 2 `&.#:` into a number: 562.
> 5 votes

# Answer
# Charcoal, ~~21~~ 18 bytes

```
Ｗ⊖Ｌθ⊞θ⊖×⊕⊗⊟θＸ²⊟θＩθ

```

Try it online! Now uses @xnor's pairing function. Previous 21-byte answer:

```
Ｗ⊖Ｌθ⊞θΣＥ²×⊕κ↨↨⊟θ²¦⁴Ｉθ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｗ⊖Ｌθ

```

Repeat until there is only one element left (i.e. reduce right)...

```
⊞θΣＥ²×⊕κ↨↨⊟θ²¦⁴

```

Convert the last two elements to base 2 and then back from base 4, double one of them and take the sum, pushing the result back to the list. This is equivalent to interleaving their bits. I use this bijection rather than the Cantor pairing function as it only requires reading each value once, thus making it golfier in Charcoal.

```
Ｉθ

```

Output the final result.
> 4 votes

# Answer
# Jelly, 6 bytes

Probably caird's 6 byter...

```
+RS+ʋ/

```

**Try it online!**

How?

Implements a repeated application of the Cantor pairing function.

A single application is \\$f(a,b)=\frac{1}{2}(a+b)(a+b+1)+b\\$

But note that \\$\frac{1}{2}(a+b)(a+b+1)=\sum\_{i=1}^{a+b}i\\$

So \\$f(a,b)=b+\sum\_{i=1}^{a+b}i\\$

```
+RS+ʋ/ - Link: list of non-negative integers
     / - reduce by:
    ʋ  -   last four links as a dyad - f(a,b)
+      -     add     -> a+b
 R     -     range   -> [1,2,3,...,a+b]
  S    -     sum     -> (a+b)(a+b+1)/2
   +   -     add (b) -> b+(a+b)(a+b+1)/2

```
> 4 votes

# Answer
# Python 2, 38 bytes

```
f=lambda a,*l:l and(a-~a<<f(*l))-1or a

```

Try it online!

Takes input splatted like `f(1,2,3)`.

Uses the pairing function \\$p(a,b)=(2a+1)2^b\\$. We use bit-shift `<<b` to shorten `*2**b`, and write `a-~a` to save a byte off of `2*a+1`.

**41 bytes**

```
lambda l:reduce(lambda a,b:(a-~a<<b)-1,l)

```

Try it online!
> 4 votes

# Answer
# Jelly, 7 bytes

```
+‘c2+µ/

```

Try it online!

0 is a natural number.

Implements Cantor Pairing, and reduces the list over that.

(There's a 6 byte solution apparently so I'm sad)

Cantor Pairing is bijective (I'm not sure of the proof but this is well known I think), so since compositions of bijections are bijective, this is bijective. In the edge case that n = 1, this is identity, so it's still bijective.

At least, that's how I think that works. Please let me know if you find an unmapped value or a collision.
> 3 votes

# Answer
# Haskell, 27 bytes

```
foldr1(\a b->2^a*(2*b+1)-1)

```

Try it online!

Uses a different bijection from the Cantor pairing function. Every positive integer can be uniquely split into a power of 2 times an odd number, that is \\$2^a(2b+1)\\$ for non-negative integers \\$a,b\\$. Subtracting 1 then means we get all non-negative integers including 0.

Here's a table for the bijection, for \\$a,b\\$ from 0 to 6:

```
  0   2   4   6   8  10  12 ...
  1   5   9  13  17  21  25
  3  11  19  27  35  43  51
  7  23  39  55  71  87 103
 15  47  79 111 143 175 207
 31  95 159 223 287 351 415
 63 191 319 447 575 703 831
 ...                        ...

```
> 3 votes

# Answer
# JavaScript (ES6), 33 bytes

Cantor pairing on the input array `a[]`.

```
a=>a.reduce((x,y)=>y-(x+=y)*~x/2)

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~10~~ 9 bytes

```
Å«+LOy+}н

```

Try it online or verify all test cases.

Port of *@ovs*' APL answer, so make sure to upvote him!
-1 byte thanks to *@ovs*.

**9 bytes alternative:**

```
ćsvy+LOy+

```

Try it online or verify some more test cases.

**Explanation:**

```
Å«         # Cumulative right-reduce by (unfortunately keeping all intermediate steps):
  +        #  Add them together: a+b
   L       #  Pop and push a list in the range [a+b]
    O      #  Sum this list
     y+    #  Add a to it
 }н        # After the reduce-by, pop the list and leave just the first item
           # (after which it is output implicitly as result)

ć          # Extract head of the (implicit) input-list; pushing the remainder-list
           # and first item separated to the stack
 s         # Swap so the remainder-list is at the top
  v        # Loop over each integer `y` in this list:
   y+      #  Add the current integer `y` to the top value
     L     #  Pop and push a list in the range [1,n]
      O    #  Sum this list
       y+  #  And add `y` to it
           # (after the loop, the integer is output implicitly as result)

```
> 2 votes

# Answer
# Scala, 34 bytes

```
_.reduce((x,y)=>(x+y)*(x+y+1)/2+y)

```

Try it online

An anonymous function of type `Seq[Int] => Int`. Applies the cantor pairing to two elements until the result is an a single integer.
> 1 votes

# Answer
# Haskell, 31 bytes

```
foldl1(\x y->(x+y)*(x+y+1)/2+y)

```

Try it online!
> 1 votes

# Answer
# C (gcc), <sup>~~62~~ \\$\cdots\\$ ~~56~~</sup> 55 bytes

Saved a byte thanks to ceilingcat!!!

```
f(a,l)int*a;{l=l?*++a=*a-(*a+=a[1])*~*a/2,f(a,l-1):*a;}

```

Try it online!

Inputs an array of natural numbers and its length minus \\$1\\$ and returns a unique natural number using Cantor pairing.
> 1 votes

# Answer
# Husk, 7 bytes

```
FS+ȯΣḣ+

```

Try it online!

Recursive Cantor pairing (same approach as HyperNeutrino's answer).

```
FS+ȯΣḣ+
F           # Fold over list (=recursively apply to pairs):
 S+ȯΣḣ+     # Cantor-pairing bijection:
 S          # Hook: combine 2 functions using same (first) argument
  +         # add first argument to
   ȯ        # combination of 2 3 functions:
    Σ       # sum of
     ḣ      # series from 1 up to
      +     # sum of first & second arguments

```
> 1 votes

# Answer
# Retina, 59 bytes

```
.+
*
+`(_+)\1
$1@
@_
_
^'@P`.+
N$`.
$.%`
¶

_
@_
+`_@
@__
_

```

Try it online! Explanation:

```
.+
*
+`(_+)\1
$1@
@_
_

```

Convert the input to binary, using `@` for `0` and `_` for `1`.

```
^'@P`.+

```

Left-pad all lines with `@` to the same length.

```
N$`.
$.%`
¶

```

Transpose and join the lines.

```
_
@_
+`_@
@__
_

```

Convert from binary to decimal.
> 1 votes

---
Tags: code-golf, math, number, open-ended-function
---


title: The Great, White, North!

text:
# Question
Title: The Great, White, North!
## Eh!

You know, the problem with us Canadians is that sometimes, after a long day of moose hunting and dam repairing, we forget our way back to our cabins! Wouldn't it be great if our handy laptop (which, is always at our side), had some way to point us home? Well, it's been long told that, if you display a compass on your computer, it will be the brightest when pointed North. I'd like to test this out, but I need a compact program to take with me on my next trip, because my hard drive is already filled with maple syrup recipes (and those CANNOT go). So, your task is to design me a program which, when run, saves or displays an image of the following compass rose:

The letters may be in a different font. Remember, least is best, so lowest byte count wins!

## Specifications

**Colors**

* Light purple: #9999FF
* Gray: #E5E5E5

**Lengths and Angles**

* Angle `a` = 45°
* Angle `b` = 90°
* Length `c` = 250 units
* Length `d` = 200 units
* Length `e` = 40 units
* Length `f` = 45 units

**Clarifications**

* The text may be in any ***appropriate*** font, where appropriate denotes that it is readable to the average, educated human being.
* The text must be 3 units away from the spikes at its closest point, must not touch the rose, and must be upright
* If a line is drawn from the center of the rose, through the end point of the spike and beyond, it should cross through the center of the text with a precision of +/- 2 units (the text must be centered along an axis `a`, where `a` extends from the middle of the page, through the end of the spike, and beyond)
* Each character must be at least 15 units by 15 units, and have an x/y or y/x ratio of no more than 2:1 (no stretching – readability)
* The dim circle passing through the longer spikes and text closest to the middle on the reference image is not to be drawn.
* The image must be square, and at least 400px by 400px
* A compressed image within the source is disallowed
* A unit must be at least 1 pixel

# Answer
> 7 votes
## HTML + CSS, 487 + 189 = 676

The compass rose is constructed from CSS borders using the triangle technique and some basic transformations. The letters are just given fixed positions, so that turned out quite long :/

The snippet below is scaled down so that it all fits. You can check out the JSFiddle here. Also, I'm not sure how well the letters will line up on different browsers (with different fonts, default styles, etc.).

```
html{transform:scale(0.2)}body{margin:5em}hr{margin:0;float:left;border:250px solid transparent;border-right:58px solid #E5E5E5;border-bottom:58px solid #9999FF}a{position:fixed;width:616px;font-size:4em}#a{transform:rotate(90deg)}#b{transform:rotate(270deg)}#c{transform:rotate(180deg)}#d{transform:rotate(45deg)scale(.8)}#n{top:20px;left:365px}#e{top:356px;left:700px}#s{top:700px;left:370px}#w{top:356px;left:10px}#N{top:150px;left:550px}#E{top:560px;left:550px}#S{top:560px;left:140px}#W{top:150px;left:140px}
```

```
<a id=n>N</a><a id=e>E</a><a id=s>S</a><a id=w>W</a><a id=N>NE</a><a id=E>SE</a><a id=S>SW</a><a id=W>NW</a><a id=d><hr><hr id=a><hr id=b><hr id=c></a><a><hr><hr id=a><hr id=b><hr id=c></a>
```

# Answer
> 3 votes
# Processing 2 - 636

A quick solution that just draws all the triangles using the processing triangle method and then places the letters at their tips.

```
int s,h,m,b,n,t;void setup(){s=400;h=s/2;b=125;t=71;n=32;m=28;size(s,s);noStroke();fill(229);t(h-t,h-t,h-m,h);t(h-t,h+t,h,h+m);t(h+t,h-t,h,h-m);t(h+t,h+t,h+m,h);fill(#9999FF);t(h-t,h-t,h,h-m);t(h-t,h+t,h-m,h);t(h+t,h-t,h+m,h);t(h+t,h+t,h,h+m);t(h-b,h,h-n,h-n);t(h+b,h,h+n,h+n);t(h,h-b,h+n,h-n);t(h,h+b,h-n,h+n);fill(229);t(h-b,h,h-n,h+n);t(h+b,h,h+n,h-n);t(h,h-b,h-n,h-n);t(h,h+b,h+n,h+n);fill(color(0));text("NW",h-t-14,h-t-2);text("NE",h+t+2,h-t-2);text("SW",h-t-14,h+t+10);text("SE",h+t,h+t+10);text("N",h-5,h-b-5);text("S",h-5,h+b+12);text("E",h+b+2,h+5);text("W",h-b-14,h+5);}void t(int a,int b,int c,int d){triangle(h,h,a,b,c,d);}

```

you can get processing here

# Answer
> 3 votes
# PHP, 628 bytes

added a few linebreaks for convenience.

```
$c=$z.create;$h=$c($w=250,$w);$i=$c(530,533);$a=$z.colorallocate;$a($h,$f=255,$f,$f);$a($i,$f,$f,$f);$a($h,229,229,229);$a($h,153,153,$f);
$p=$z.filledpolygon;$p($h,$o=[0,64,0,0,141,141,],3,2);$p($h,[64,0]+$o,3,1);$p($h,$o=[0,$w,0,0,57,57],3,1);$p($h,[$w,0]+$o,3,2);
$c=$z.copy;$r=$z.rotate;$c($i,$h,263,267,0,0,$w,$w);$c($i,$r($h,90,0),263,17,0,0,$w,$w);$c($i,$r($h,180,0),13,17,0,0,$w,$w);$c($i,$r($h,270,0),13,267,0,0,$w,$w);
$s=$z.string;$s($i,5,259,0,N,3);$s($i,5,259,518,S,3);$s($i,5,0,259,W,3);$s($i,5,518,259,E,3);$s($i,5,106,108,NW,3);$s($i,5,406,108,NE,3);$s($i,5,406,410,SE,3);$s($i,5,106,410,SW,3);
imagepng($i,"n.png");

```

Run with `-r`. Creates a file `n.png` with the image; unit is 2 pixels.

I must admit I found the coords for the winds by trial & error, and they are probably a bit off. Will do the calculations soon; but I promise: they won´t change the byte count.
Had my fun for now excavating my trignonometry and struggling with `imagecopy` ... what a sissy!

on golfing: not many tricks; but these few saved a lot:

* Assigning function names and two of the values to variables probably had the largest impact.
I didn´t even count before I replaced the function names.
* The magic with the array `+` operator gave 42 bytes.
* Writing a file instead of sending the image to the browser saved 27 bytes.
* Moving assignments to the first usage of the variables gave a few more.

**breakdown**

```
// create images and allocate colors
$c=imagecreate;
$h=$c($w=250,$w);   // helper image - just as large as needed or imagecopy will screw up
$i=$c(530,533);     // main image

$a=imagecolorallocate;
$a($h,$f=255,$f,$f);    // white is 0
$a($i,$f,$f,$f);    // must be assigned to both images
$a($h,229,229,229); // grey is 1
$a($h,153,153,$f);  // purple is 2

// draw the south-east quadrant
$p=imagefilledpolygon;
// small triangle purple first
$p($h,$o=[
// point 3: 0.8*e *2
    0,64,
// point 1: center
    0,0,
// point 2: a=45 degrees, d=200 units
    141,141,// d/sqrt(2)=141.421356
],3,2);
// small triangle grey
$p($h,[64,0]+$o,3,1);

// large triangles
$p($h,$o=[
    0,$w,
    0,0,
    57,57   // e*sqrt(2)=56.5685424949
],3,1);

$p($h,[$w,0]+$o,3,2);

// create rose
$c=imagecopy;
$r=imagerotate;
$c($i,$h,263,267,0,0,$w,$w);            // copy quadrant to main image (SE)
$c($i,$r($h,90,0),263,17,0,0,$w,$w);    // rotate quadrant and copy again (NE)
$c($i,$r($h,180,0),13,17,0,0,$w,$w);    // rotate and copy again (NW)
$c($i,$r($h,270,0),13,267,0,0,$w,$w);// rotate and copy a last time (SW)

// add circle
#imageellipse($i,263,267,500,500,2);    // grey is now 2: imagecopy shuffled colors

// add names
$s=imagestring;
$s($i,5,259,  0,N,3);   // 5 is actually the largest internal font PHP provides
$s($i,5,259,518,S,3);   // unassigned colors are black
$s($i,5,  0,259,W,3);
$s($i,5,518,259,E,3);

$s($i,5,106,108,NW,3);
$s($i,5,406,108,NE,3);
$s($i,5,406,410,SE,3);
$s($i,5,106,410,SW,3);

// output
#header("Content-Type:image/png");
#imagepng($i);
imagepng($i,"n.png");

```

# Answer
> 3 votes
# Java 8, 756 bytes

```
import java.awt.*;v->new Frame(){void t(Graphics g,String s,int x,int y){g.drawString(s,x,y);}public void paint(Graphics g){g.setFont(new Font("Hei",0,30));t(g,"N",289,80);t(g,"E",553,341);t(g,"S",290,605);t(g,"W",20,341);t(g,"NE",434,186);t(g,"SE",437,496);t(g,"SW",120,498);t(g,"NW",121,186);g.setColor(new Color(229,229,229));g.fillPolygon(new int[]{300,346,442,390,550,390,442,346,300,254,158,210,50,210,158,254},new int[]{80,240,188,284,330,376,472,420,580,420,472,376,330,284,188,240},16);g.setColor(new Color(153,153,255));g.fillPolygon(new int[]{300,158,254,244,50,300,158,210,244,300,300,442,346,356,550,300,442,390,356,300},new int[]{330,188,240,274,330,330,472,376,386,580,330,472,420,386,330,330,188,284,274,80},20);}{setSize(600,630);show();}}

```

Output:

## Explanation:

**Code explanation:**

```
import java.awt.*;          // Required import for Frame, Graphics, Font, and Color
v->                         // Method with empty unused parameter and Frame return-type
  new Frame(){              //  Create a new Frame
    void t(Graphics g,String s,int x,int y){
                            //   Create a temp method to reduce bytes:
      g.drawString(s,x,y);} //    To draw the given text at the given coordinate
    public void paint(Graphics g){
                            //   Overwrite the Frame's default paint method:
      g.setFont(new Font("Hei",0,30));
                            //    Set the Font to size 30
                            //    (I've used Font "Hei" here, but "Kai" could be used as
                            //     well for the same byte-count)
      t(g,"N",289,80);      //    Draw the text "N"
      t(g,"E",553,341);     //    Draw the "E"
      t(g,"S",290,605);     //    Draw the "S"
      t(g,"W",20,341);      //    Draw the "W"
      t(g,"NE",434,186);    //    Draw the "NE"
      t(g,"SE",437,496);    //    Draw the "SE"
      t(g,"SW",120,498);    //    Draw the "SW"
      t(g,"NW",121,186);    //    Draw the "NW"
      g.setColor(new Color(229,229,229));
                            //    Change the color to grey
                            //    (the default color was black, which is why we started
                            //     with the texts)
      g.fillPolygon(new int[]{300,346,442,390,550,390,442,346,300,254,158,210,50,210,158,254},new int[]{80,240,188,284,330,376,472,420,580,420,472,376,330,284,188,240},16);
                            //    Draw the 8-pointed star
      g.setColor(new Color(153,153,255));
                            //    Change the color to light purple
      g.fillPolygon(new int[]{300,158,254,244,50,300,158,210,244,300,300,442,346,356,550,300,442,390,356,300},new int[]{330,188,240,274,330,330,472,376,386,580,330,472,420,386,330,330,188,284,274,80},20);}
                            //    Draw a single shape as explained below
    {                       //   In an inner code block:
      setSize(600,630);     //    Set the size of the Frame
      show();}}             //    And show the Frame

```

**Calculations:**

Although Java has ways to draw based on rotations, it would increase the byte-count substantial in comparison to this straight-forward approach. There is however one main disadvantage about using this shorter approach: I have to calculate all \\$x,y\\$-coordinates manually..
So, here's how I did that:

I first used the units as is, since that was easier to calculate with. I've put the center at position \\$150,150\\$ and started calculating from there.

*1) Calculate the coordinates of the tips of the star at N/E/S/W:*

This is not too hard. With the center at \\$150,150\\$ and \\$\frac{\color{red}{c}}{2} = 125\\$, we'll have the following points:

\\$N=150,25\\$
\\$E=275,150\\$
\\$S=150,275\\$
\\$W=25,100\\$

*2) Calculate the coordinates of the tips of the star at NE/SE/SW/NW:*

Again, we know the center is at \\$150,150\\$ and we also know \\$\frac{\color{blue}{d}}{2}=100\\$. We can make a triangle calculation with the angles being 90, 45, and 45 like this:

\\$n=\frac{100}{2}\sqrt{2}=70.710\dots\\$
(where \\$m\\$ are the sides \\$b\\$ and \\$c\\$ in the triangle above)

Knowing the \\$n\\$, we have the following points:

\\$NE=150+m,150-m=220.710\dots,79.289\dots\\$
\\$SE=150+m,150+m=220.710\dots,220.710\dots\\$
\\$SW=150-m,150+m=79.289\dots,220.710\dots\\$
\\$NW=150-m,150-m=79.289\dots,79.289\dots\\$

*3) Calculate the coordinates of the points between the center and the NE/SE/SW/NW tips:*

We again know the center \\$150,150\\$ and also \\$\color{violet}{e}=40\\$, so we can make a similar calculation as in step 2:

\\$n=\frac{40}{2}\sqrt{2}=28.284\dots\\$

And use that to calculate the points:

\\$NE\_{center}=150+n,150-n=178.284\dots,121.715\dots\\$
\\$SE\_{center}=150+n,150+n=178.284\dots,178.284\dots\\$
\\$SW\_{center}=150-n,150+n=121.715\dots,178.284\dots\\$
\\$NW\_{center}=150-n,150-n=121.715\dots,121.715\dots\\$

*4) Calculate the coordinates of the remaining points:*

Now all that's left are the points at the concaved intersection of the edges of the star, which are circled in red here:

Since we know the center \\$150\\$ and \\$\color{lightblue}{f}=45\\$, a portion of these coordinates aren't hard to calculate. The other part of the coordinates requires some calculations, though..

In the picture above, we know the following things beforehand:

* Red line: \\$\frac{\color{red}{c}}{2}=125\\$
* Both orange lines: \\$n=\frac{40}{2}\sqrt{2}=28.284\dots\\$

And what we want to calculate is the thick vertical blue line of the small purple triangle.

We start with the horizontal line of the larger green triangle:
\\$o=125-n=96.715\dots\\$

Using what we know now, we can calculate the black angle of the large green triangle as follows:

\\$t=\sqrt{n^2+o^2-2no\times\cos(90)}=100.765\dots\\$
\\$A=\arccos(\frac{t^2+o^2-n^2}{2to})=16.301\dots\\$

Then we can calculate the light blue angle of the small purple triangle:

\\$B=90-16.301\dots=73.699\dots\\$

As well as the horizontal line of the small purple triangle:

\\$p=45-n=16.716\dots\\$

Which we can then both use to calculate the height of the thick blue line of the small purple triangle:

\\$q=p\frac{\sin(A)}{\sin(B)}=4.888\dots\\$

After which we can finally calculate the final coordinates of these red dots, using the center and the points we've calculated in step 2:

\\$NE\_N=178.284\dots-q,150-\color{lightblue}{f}=173.395\dots,105\\$
\\$NE\_E=150+\color{lightblue}{f},121.715\dots+q=195,126.604\dots\\$
\\$SE\_E=150+\color{lightblue}{f},178.284\dots-q=195,173.395\dots\\$
\\$SE\_S=178.284\dots-q,150+\color{lightblue}{f}=173.395\dots,195\\$
\\$SW\_S=121.715\dots+q,150+\color{lightblue}{f}=126.604\dots,195\\$
\\$SW\_W=150-\color{lightblue}{f},178.284\dots-q=105,173.395\dots\\$
\\$NW\_W=150-\color{lightblue}{f},121.715\dots+q=105,126.604\dots\\$
\\$NW\_N=121.715\dots+q,150-\color{lightblue}{f}=126.604\dots,105\\$

---

We now have all the coordinates of the points we need, so we can draw the shape on the screen. We do this with the `Graphics#fillPolygon(int[],int[],int)`-method, which takes two integer-arrays for all \\$x\\$\- and \\$y\\$-coordinates respectively, as well as an integer being the amount of points. The grey star is therefore drawn using the following \\$x,y\\$-coordinates:
\\$\[\[150,25\],\[173,105\],\[221,79\],\[195,127\],\\$
\\$\[275,150\],\[195,173\],\[221,221\],\[173,195\],\\$
\\$\[150,275\],\[127,195\],\[79,221\],\[105,173\],\\$
\\$\[25,150\],\[105,127\],\[79,79\],\[127,105\]\]\\$:

We then draw a single shape for the light purple parts, and the following \\$x,y\\$-coordinates:
\\$\[\[150,150\],\[79,79\],\[127,105\],\[122,122\],\[25,150\],\\$
\\$\[150,150\],\[79,221\],\[105,173\],\[122,178\],\[150,275\],\\$
\\$\[150,150\],\[221,221\],\[173,195\],\[178,178\],\[275,150\],\\$
\\$\[150,150\],\[221,79\],\[195,127\],\[178,122\],\[150,25\]\]\\$:

A quarter of this shape goes from the center to point \\$NW\\$; then to point \\$NW\_N\\$; then \\$NW\_{center}\\$; then \\$W\\$; and then back to the center again:

And the entire shape is drawn by continuing in a similar fashion.

---

After that I've doubled everything, because the challenge description states the square should be at least 400 by 400 pixels, and in addition all \\$y\\$-coordinates are increased by \\$30\\$, because we draw directly on the frame and we still have the Window-bar at the top to consider (outside codegolf you would add a Panel to the Frame, and draw on that, but drawing directly on the Frame is also possible and -in this case- 1 byte shorter ¯\\\_(ツ)\_/¯).

And finally we add the text, for which no calculations are used. In the used Font the letters aren't monospace (W is for example larger than S), and in Java everything is drawn from the top-left \\$x,y\\$-coordinate, so we can't really make any smart calculations here tbh. I've just added some temporary red lines going beyond the points and manually adjusted the text positions a bit:

If you think they aren't correct, they can be moved slightly by adjusting the coordinates, without changing the byte-count.
For those curious, here are the adjustments made to the coordinates of the tips to position the texts:

\\$N=300-11, 80\\$
\\$E=550+3,330+11\\$
\\$S=275+15,580+25\\$
\\$W=50-30,330+11\\$
\\$NE=441-7,188-2\\$
\\$SE=441-4,471+25\\$
\\$SW=158-38,471+27\\$
\\$NW=158-37,188-2\\$

And well, that's it. Thank you for listening to my TED talk about drawing a compass in Java. :)

# Answer
> 1 votes
## R, ~~877~~ ~~850~~ 813

Lot's of room to golf this I suspect, but I wanted to get something up to see if I managed to comply with the rules.

Edit: Lost a few cleaning up around the polygon creation, gained a few removing outlines

```
a=45;b=90;c=125;e=40;h=c(0,0,b,a,a,0,a,b)*pi/180;i=c(0,c,c,100,e,a,(2*a^2)^.5,a);x=i*sin(h);y=i*cos(h);q=x[6:7];r=x[7:8];s=x[2:3];t=x[c(5,5)];u=y[6:7];v=y[7:8];w=y[2:3];z=y[c(5,5)];m=(s-t);n=(w-z);o=(q-r);p=(u-v);i=((q*v-u*r)*m-o*(s*z-w*t))/(o*n-p*m);x=c(x,i)[c(1,2,5,1,3,5,5,4,10,5,4,9)];y=c(y,rev(i))[c(1,2,5,1,3,5,5,4,10,5,4,9)];png("1.png",400,400);par(mar=rep(0,4));a=c(-200:200);plot(a,a,type="n");for(b in 0:3){for(i in(0:3)*3+1){a=c(1,1,1,-1,-1,-1,-1,1);polygon(x[(i):(i+3)]*a[b*2+1],y[(i):(i+3)]*a[b*2+2],border=NA,col=c("#9999FF","#E5E5E5")[(i%%6%/%4+b%%2)%%2+1]);}};for(i in 1:4){a=c("N","NE","E","SE","S","SW","W","NW");b=a[i*2-1];c=a[i*2];o=c(1,1,-1,-1,1);n=o[i+1];m=o[i];e=c(5,2)[i%%2+1];text((x[e]+(11*abs(i%%2-1)))*m,(y[e]+(12*i%%2))*n,b,cex=1.8);text((x[8]+10)*m,(y[8]+12)*n,c,cex=1.8)};dev.off()

```

This produces the following png image

A bit of an explanation of what I'm doing

```
a=45;
b=90;
c=125;
e=40;
h=c(0,0,b,a,a,0,a,b)*pi/180;            # angles to known vertices in one quadrant
i=c(0,c,c,100,e,a,(2*a^2)^.5,a);        # distances to known vertices
x=i*sin(h);                             # calculate x ordinates
y=i*cos(h);                             # calculate y ordinates
q=x[6:7];                               #-----------------------
r=x[7:8];                               #
s=x[2:3];                               # Get the lines required
t=x[c(5,5)];                            # to determine the vertex
u=y[6:7];                               # for the minor pointers
v=y[7:8];                               #
w=y[2:3];                               #
z=y[c(5,5)];                            #------------------------
m=(s-t);                                # Intersect them
n=(w-z);                                # to give coordinate.
o=(q-r);                                # Just calculate the x's
p=(u-v);                                # as they can be reversed
i=((q*v-u*r)*m-o*(s*z-w*t))/(o*n-p*m);  #------------------------
x=c(x,i)[c(1,2,5,1,3,5,5,4,10,5,4,9)];      # X Triangle groups
y=c(y,rev(i))[c(1,2,5,1,3,5,5,4,10,5,4,9)]; # Y Triangle groups
png("1.png",400,400);                   # Set output to png
par(mar=rep(0,4));                      # Make margins 0
a=c(-200:200);
plot(a,a,type="n");                     # Start plot
for(b in 0:3){for(i in(0:3)*3+1){       # draw polygons, alternating colors and drawing all quadrants
a=c(1,1,1,-1,-1,-1,-1,1);
polygon(x[(i):(i+3)]*a[b*2+1],y[(i):(i+3)]*a[b*2+2],border=NA,col=c("#9999FF","#E5E5E5")[(i%%6%/%4+b%%2)%%2+1]);
}};
for(i in 1:4){                          # Add text to compass points for each quadrant
a=c("N","NE","E","SE","S","SW","W","NW");b=a[i*2-1];c=a[i*2];
o=c(1,1,-1,-1,1);n=o[i+1];m=o[i];
e=c(5,2)[i%%2+1];
text((x[e]+(11*abs(i%%2-1)))*m,(y[e]+(12*i%%2))*n,b,cex=1.8);
text((x[8]+10)*m,(y[8]+12)*n,c,cex=1.8)
};
dev.off()                               # Close PNG

```

# Answer
> 1 votes
# Mathematica, 347 bytes

```
p=q={{0,0},{0,125},40{1/Sqrt[2],1/Sqrt[2]}};q[[3,1]]*=-1;m=5p[[3]]/2;s=u={{0,0},m,{32,0}};u[[3]]={0,32};r={{0,1},{-1,0}};t=Polygon[#]&;z=MatrixPower[r,#]&;a[v_]:=Table[t[z[n].#&/@v],{n,4}];i=Table[Text[#[[j]],z[j].#2],{j,4}]&;G=RGBColor["#E5E5E5"];Graphics[{i[{E,S,W,N},{0,130}],i[{NE,SE,SW,NW},1.06m],G,a[u],RGBColor["#9999FF"],a[s],a[p],G,a[q]}]

```

Pregolfed:

```
p = q = {{0, 0}, {0, 125}, 40 {1/Sqrt[2], 1/Sqrt[2]}}; (*defining points*)
q[[3, 1]] *= -1;                                       (*for triangles*)
m = 5 p[[3]]/2;
s = u = {{0, 0}, m, {32, 0}};
u[[3]] = {0, 32};
r = {{0, 1}, {-1, 0}};                                 (*-pi/2 rotation matrix*)

t = Polygon[#] &;
z = MatrixPower[r, #] &;
a[v_] := Table[t[z[n].# & /@ v], {n, 4}];              (*rotate the sets of points*)
                                                       (*four times*)

i = Table[Text[#[[j]], z[j].#2], {j, 4}] &;
G = RGBColor["#E5E5E5"];                               (*need to use this twice*)
                                                       (*so triangles overlap*)
                                                       (*properly so define a variable*)

Graphics[{i[{E, S, W, N}, {0, 130}],
  i[{NE, SE, SW, NW}, 1.06 m], G, a[u], RGBColor["#9999FF"], a[s],
  a[p], G, a[q]}]

```

`N` and `E` (base of the natural log) are both built-ins in Mathematica but as text E gets stylized into a lowercase font you see in the image but the problem doesn't *quite* say we can only use one font for all the text. If that is a requirement then replace `E` with `"E"` and I gain two bytes.

`Sqrt[2]` in Mathematica can be stylized into two characters, so if we count each `Sqrt[2]` as two characters then my new byte count is 339 instead of 349.

The image below is produced.

---
Tags: code-golf, graphical-output
---


title: A Megachess Board

text:
# Question
Title: A Megachess Board
You want to create a square chessboard. Adjacent tiles must alternate black and white like a standard chessboard, and the bottom left corner can be either black or white.

Your program will take in two positive integers, the number of black and the number of white tiles. These will always be less than 1024. You don't have to use all the tiles.

Output the maximum side length of a chessboard pattern that can be constructed using the given amount of tiles.

Test Cases:

```
12, 15 -> 5
8, 8 -> 4
4, 0 -> 1

```

# Answer
# JavaScript (ES7), 30 bytes

```
b=>w=>((b<w?b:w)*2|b!=w)**.5|0

```

Try it online!

Given the number of black squares \\$b\\$ and the number of white squares \\$w\\$, this computes:

$$s=\left\lfloor\sqrt{2\times\min(b,w)+k}\right\rfloor$$ with: $$k=\begin{cases} 0&\text{if }b=w\\ 1&\text{if }b\neq w \end{cases}$$

For even sizes \\$s\\$, we need \\$s^2/2\\$ squares of each kind (e.g. for \\$s=8\\$: \\$32\\$ black squares and \\$32\\$ white squares).

For odd sizes \\$s\\$, we need \\$\lfloor s^2/2\rfloor\\$ squares of one kind and \\$\lceil s^2/2\rceil\\$ squares of the other kind (e.g. for \\$s=5\\$: \\$12\\$ black squares and \\$13\\$ white squares, or the other way around). The parameter \\$k\\$ is set to \\$1\\$ if \\$max(b,w)\geq min(b,w)+1\\$, which represents this extra square on one side.
> 11 votes

# Answer
# Jelly, 6 bytes

```
«Ḥ+nÆ½

```

Try it online!

A dyadic link that returns the maximum board size.

Test suite for all permutations of numbers to 20

### Explanation

```
«      | Minimum
 Ḥ     | Doubled
  +n   | Plus 1 if inputs not equal
    Æ½ | Integer square root

```

Arnauld’s answer has a good explanation for *why* this works; please consider upvoting him too!
> 6 votes

# Answer
# Haskell, 35 bytes

```
x#y=floor$sqrt$min(x+y)$1+2*min x y

```

Try it online!

## Explanation

This answer calculates the following formula:

$$\left\lfloor\sqrt{\min(a+b,2\min(a,b)+1)}\right\rfloor$$

Why does this formula work? Well lets start by noting the following:

*Every square of even side length can be tiled by \\$2\times 1\\$ tiles.*

and

*Every square of odd length can be tiled, spare a single \\$1\times 1\\$ square, by \\$2\times 1\\$ tiles.*

Now we note that if we put these \\$2\times 1\\$ tiles on a chessboard each would lay on top of one black square and on white square. So if we make an even chessboard every tile needs to have a pair of the other color, and if we make an odd chessboard every tile but one needs a pair of the other color. This tells us that the answer is never more than \\$\left\lfloor\sqrt{2\min(a,b)+1}\right\rfloor\\$. \\$2\min(a,b)\\$ is the maximum number of pairs we can make and the \\$+1\\$ is for the last square that doesnt' need a pair. The problem with this is that if \\$a=b\\$ we will not have the extra square for the odd case. So we add another condition: Our result cannot be more than \\$\left\lfloor\sqrt{a+b}\right\rfloor\\$. That is we can't make a square which has more tiles than we have available.

So we just take the lesser of the two options.

$$\left\lfloor\sqrt{\min(a+b,2\min(a,b)+1)}\right\rfloor$$

We can notice that this is the same as Arnauld's formulation since if \\$a=b\\$ then \\$2\min(a,b)\\$ is just \\$a+b\\$.
> 5 votes

# Answer
# Ruby, 36 bytes

```
->x,y{'%i'%[x+y,x-~x,y-~y].min**0.5}

```

Try it online!

`x-~x` is a golfed version of `2*x+1`; we're subtracting x's twos-complement negation from itself. After that I'm just using this answer's formula, but collapsing the two nested `min`s into one, then using string formatting to truncate to an integer.
> 3 votes

# Answer
# Retina 0.8.2, 50 bytes

```
O#`\d+
\d+
$*
(1*),(1?\1)1*
$1$2
^(^1|11\1)*1*
$#1

```

Try it online! Link includes test cases. Explanation:

```
O#`\d+

```

Sort the numbers in ascending order. Let's call them `l` and `h`.

```
\d+
$*

```

Convert to unary.

```
(1*),(1?\1)1*
$1$2

```

Compute `l + max(h, l + 1)`. This is the equivalent to `2 * min(b, w) + (b != w)`. See @Arnauld's answer for why this works.

```
^(^1|11\1)*1*
$#1

```

Find the highest integer square root.
> 2 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
Ë≠+ß·tï

```

Try it online or verify all test cases.

**Exlanation:**

Uses a trivial derivative of the formula *@Arnauld* used in his JavaScript answer to save a byte:

$$s=\left\lfloor\sqrt{2\times\min(b+k,w+k)}\right\rfloor$$ with still: $$k=\begin{cases} 0&\text{if }b=w\\ 1&\text{if }b\neq w \end{cases}$$

```
Ë        # Check if the two values of the (implicit) input-pair are the same
         #  (1 if truthy; 0 if falsey)
 ≠       # Falsify (!= 1), so 1 becomes 0 and vice-versa
  +      # Add that to each of the (implicit) input-values
   ß     # Only leave the minimum of that
    ·    # Double it
     t   # Take the square root
      ï  # And truncate/floor it by casting to an integer

```
> 2 votes

# Answer
# Japt, 11 bytes

Port of Arnauld's JS solution. Takes input as an array.

```
ñÍÌÑ+Ur¦)¬f

```

Try it

```
ñÍÌÑ+Ur¦)¬f     :Implicit input of array U
ñ               :Sort by
 Í              :  Subtracting from 2
  Ì             :Last element (Yes, there are more straightforward ways of getting the minimum but I like this method and it doesn't cost any bytes)
   Ñ+           :Multiply by 2 and add
     Ur         :U reduced by
       ¦        :  Testing for inequality
        )       :End reduce
         ¬      :Square root
          f     :Floor

```
> 1 votes

# Answer
# Perl 6, ~~29~~ 26 bytes

```
{0+|sqrt 2*@_.min+[!=] @_}

```

Thanks to Jo King for -3 bytes.

Try it online!
> 1 votes

# Answer
# , 32 bytes

```
min(sum(n<-scan()),2*n+1)^.5%/%1

```

Try it online!

Takes `b` and `w` from stdin.

Uses the formula from this answer, but leveraging the behavior of `min` to take the minimum of all its arguments.
> 1 votes

# Answer
# Japt, 10 bytes

Port of Arnauld's JS solution.

```
mV Ñ|U¦V ¬

```

Try it online!
> 0 votes

# Answer
# Husk, 9 bytes

```
⌊√+¬=³¹Dy

```

Try it online! Uses the logic from Arnauld's answer.
> 0 votes

# Answer
# Python 3, 37 bytes

```
lambda a,b:(2*min(a,b)+(a!=b))**.5//1

```

Try it online!

Port of Arnauld's solution.
> 0 votes

---
Tags: code-golf
---


title: Find relevant digit groupings

text:
# Question
Title: Find relevant digit groupings
Recently, my reputation was `25,121`. I noticed that each digit grouping (i.e. the numbers separated by commas) was a perfect square.

Your challenge is, given a non-negative integer **N** and a unary boolean Black Box Function *f* : **Z<sup>*</sup>****B** , yield a truthy value if each value of *f* applied to the digit groupings of **N** is truthy, and falsey otherwise.

One can find the digit groupings by splitting the number into groups of 3, starting from the right side. The leftmost group may have 1, 2, or 3 digits. Some examples:

```
12398123  -> 12,398,123    (3 digit groupings)
10        -> 10            (1 digit grouping)
23045     -> 23,045        (2 digit groupings)
100000001 -> 100,000,001   (3 digit groupings)
1337      -> 1,337         (2 digit groupings)
0         -> 0             (1 digit grouping)

```

## Additional rules

* This function can map to either booleans (e.g. `true` and `false`), `1`s and `0`s, or any truthy/falsey value. Please specify which format(s) are supported by your answer.
* You may take an integer as input, or an integer string (i.e. a string composed of digits).
* You may write a program or a function.
* When passing the digital groups to the function *f*, you should trim all unnecessary leading zeroes. E.g., *f*, when applied to **N** = 123,000 should be executed as *f*(123) and *f*(0).

## Test cases

Function notation is `n -> f(n)`, e.g., `n -> n == 0`. All operators assume integer arithmetic. (E.g., `sqrt(3) == 1`)

```
function f
integer N
boolean result

n -> n == n
1230192
true

n -> n != n
42
false

n -> n > 400
420000
false

n -> n > 0
0
false

n -> n -> 0
1
true

n -> sqrt(n) ** 2 == n
25121
true

n -> sqrt(n) ** 2 == n
4101
false

n -> mod(n, 2) == 0
2902414
true

n -> n % 10 > max(digits(n / 10))
10239120
false

n -> n % 10 > max(digits(n / 10))
123456789
true

```

# Answer
> 4 votes
# Jelly, 5 bytes

```
bȷÇ€Ạ

```

Try it online!

The command-line argument is the number. The line above the line this function resides in is the main line of the rest of the program, that is, the code that gets called for each of the groups. **Be careful not to refer to the line `bȷÇ€Ạ` is in!** The example used here is the 5th test case.

# Answer
> 7 votes
## Brachylog, 8 bytes

```
ḃ₁₀₀₀↰₁ᵐ

```

Try it online!

The blackbox function goes on the second line (or the "Footer" on TIO) and the integer is read from STDIN. Prints `true.` or `false.` accordingly.

```
ḃ₁₀₀₀      Compute the base-1000 digits of the input.
     ↰₁ᵐ   Map the blackbox predicate over each digit. We don't care about the
           result of the map, but the predicate must succeed for each digit,
           otherwise the entire map fails.

```

# Answer
> 5 votes
# APL (Dyalog), ~~16~~ 13 bytes

*3 bytes saved thanks to @Adám*

```
∧/⎕¨1e3⊥⍣¯1⊢⎕

```

Try it online!

**How?**

`1e3⊥⍣¯1⊢⎕` \- input the number and encode in base 1000

`⎕¨` \- input the function and apply on each

`∧/` \- reduce with logical and

# Answer
> 4 votes
# Python 2, 46 bytes

```
g=lambda f,n,k=1000:f(n%k)and(n<k or g(f,n/k))

```

Try it online!

# Answer
> 4 votes
## Haskell, ~~42~~ ~~40~~ 38 bytes

```
f#n=f(mod n 1000)&&(n<1||f#div n 1000)

```

The blackbox function must return `True` or `False`.

Try it online!

Edit: ~~-2~~ -4 bytes thanks to @ovs.

# Answer
> 4 votes
# C (gcc), ~~66~~ ~~58~~ 48 bytes

*-10 bytes thanks to @Neil!*

```
t=1000;g(f,i)int f();{i=f(i%t)&(i<t||g(f,i/t));}

```

Try it online!

# Answer
> 3 votes
## Wolfram Language (Mathematica), 30 bytes

```
And@@#/@#2~IntegerDigits~1000&

```

Try it online!

# Answer
> 3 votes
## JavaScript (ES6), ~~40~~ 36 bytes

```
f=>g=i=>f(i%1e3)&(i<1e3||g(i/1e3|0))

```

Takes the function and value by currying and returns 0 or 1. Edit: Saved 4 bytes thanks to @Shaggy.

# Answer
> 2 votes
# Pyth, 9 bytes

```
.AyMjQ^T3

```

Try it online! (uses the third test case)

Assumes the black-box function is named `y`. You can declare such a function using `L` (argument: `b`), as shown on TIO. I will implement all the test cases later, if I have time.

# Answer
> 2 votes
# Stax, 8 bytes

```
Vk|Eym|A

```

Stax programs do not have function calls or arguments, so we store a block in the `Y` register that consumes and produces a single value. This can be done before the program code.

```
{...}Yd     store a block in the Y register that executes ...
Vk|E        get "digits" of input using base 1000
    ym      map "digits" to array using y as mapping function
      |A    all elements are truthy?

```

Here's an example using the perfect square function.

# Answer
> 2 votes
# Clean, 54 bytes

```
import StdEnv
$n=if(n<1)True($(n/1000))&&f(n rem 1000)

```

Try it online!

Defines the function `$ :: Int -> Bool`, expecting a function `f :: Int -> Bool` to be defined elsewhere.

# Answer
> 2 votes
# Java (OpenJDK 9), 94 bytes

```
f->n->{int r=0,l=n.length();for(;l>0;l-=3)r+=f.test(n.substring(l<4?0:l-3,l))?0:1;return r<1;}

```

Try it online!

# Answer
> 2 votes
# Common Lisp, ~~73~~ 72 bytes

```
(defun g(x f)(and(funcall f(mod x 1000))(or(< x 1e3)(g(floor x 1e3)f))))

```

Try it online!

# Answer
> 1 votes
# Ruby, 37 bytes

```
g=->f,n{f[n%x=1000]&&(n<x||g[f,n/x])}

```

Try it online!

A recursive lambda, taking function and integer and returning boolean.

## 36 bytes (only positive n)

```
g=->f,n{n>0?f[n%k=1000]&&g[f,n/k]:1}

```

This version returns `1` for truthy, `false` for falsey. Unfortunately it can fail when `n = 0`

Try it online!

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
₄вεI.V}P

```

Try it online!

**Explanation**

```
₄в         # convert first input to base-1000
  ε   }    # apply to each element
   I.V     # execute second input as code
       P   # product of the resulting list

```

Takes the number as the first line of input and the function as the second.
Outputs **1** for truthy and **0** for falsy.

# Answer
> 1 votes
# Excel VBA, 79 bytes

An anonymous VBE immediate window function that takes input, `n` as type integer from range `[A1]`, and the name of a publically defined VBA function from range `[B1]`.

```
t=1:n=[A1]:While n:t=t*-Application.Run(""&[B1],n Mod 1E3):n=Int(n/1E3):Wend:?t

```

### Usage example

In a public module, the input function, in this case `f()` is defined.

```
Public Function f(ByVal n As Integer) As Boolean
    Let f = (n Mod 2 = 0)
End Function

```

The input variables are set.

```
[A1]=2902414    ''  Input Integer
[B1]="f"        ''  input function

```

The immediate window function is then called.

```
t=1:n=[A1]:While n:t=t*-Application.Run(""&[B1],n Mod 1E3):n=Int(n/1E3):Wend:?t
 1              ''  Function output (truthy)

```

# Answer
> 1 votes
# Appleseed, 51 bytes

```
(lambda(n f)(all(map f(or(to-base 1000 n)(q(0))))))

```

Anonymous lambda function that takes a number and a function and returns a boolean value.

Try it online!

```
(lambda (n f)         ; Function with parameters n and f
 (all                 ; Return true if all elements of this list are truthy:
  (map f              ; Map the function f to each element of
   (or                ; This list if it is nonempty:
    (to-base 1000 n)  ; Convert n to a list of "digits" in base 1000
    (q (0))           ; Or if that list is empty (when n=0), then use the list (0) instead
   ))))

```

# Answer
> 1 votes
# Add++, 15 bytes

```
L,1000$bbbUª{f}

```

Try it online!

Requires a function `f` to be declared in the TIO header.

## How it works

```
D,f,@,0.5^i2^A=	; Declares a function 'f' to check if a perfect square
		; E.g. 25 -> 1; 26 -> 0

L,		; Declare the main lambda function
		; Example argument: 		[25121]
	1000$bb	; Convert to base 1000	STACK = [[25 121]]
	bUª{f}	; Is 'f' true for all?	STACK = [1]

```

# Answer
> 0 votes
# Husk, 7 bytes

```
`ΛmrC_3

```

Try it online! Takes **N** as a string and *f* as a function object. Given a number, *f* can return any truthy or falsy value.

# Answer
> 0 votes
# Japt, 9 bytes

Had to sacrifice 3 bytes and take input as a string in order to handle the `n=>n>0` test case when `n=0`. I could get them back if it was permitted to pass the groupings to the function as strings and convert them to integers within the function, when necessary

```
ò3n)mn eV

```

Try it

The function, as allowed by consensus, is preassigned to variable `V` on the second line of the header - the empty first line is essential.

Here are all the test case functions rewritten for Japt.

```
n -> n == n                           X{X==X}
n -> n != n                           X{X!=X}
n -> n > 400                          X{X>400}
n -> n > 0                            X{X>0}
n -> n -> 0                           X{X{0}}
n -> sqrt(n) ** 2 == n                X{Xq v1}
n -> mod(n, 2) == 0                   X{X%2==0}
n -> n % 10 > max(digits(n / 10))     X{X%10>Xz10 ì rw}

```

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


# Question
Title: Replace letters by their rank, keeping punctuation intact
The problem is simple. Given a string such as `Hello World!` the program would output `8-5-12-12-15 23-15-18-12-4-!`. Any delimiters will do, (please specify what they are though) I just chose to use space between words and dashes between characters.

The conversion is that all alphabetical characters will be converted to their numeric equivalent. i.e. `A=1,B=2,...,Z=26`. All other characters must be kept intact. Case insensitive. Another example

```
Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given.
8-5-18-5-'-19 1-14-15-20-8-5-18 5-24-1-13-16-12-5-, 9 8-15-16-5 20-8-1-20 20-8-9-19 23-9-12-12 9-12-12-21-19-20-18-1-20-5 13-25 16-15-9-14-20-! 9-6 9-20-'-19 21-14-1-2-12-5-, 13-15-18-5 19-16-5-3-19 23-9-12-12 2-5 7-9-22-5-14-.

```

Note that there are no trailing or starting delimiters between characters.

Scoring will be based on the shortest amount of code. Any language is welcome.

As long as more answers are provided I will change the winner. GLHF!

# Answer
> 5 votes
## GolfScript (24 22 chars)

```
{.32|96^:@`]@(26/!=n}%

```

is a hybrid of Howard's solution and my previous one:

```
{.223&65-.26/!{)`\}*;n}%

```

Since the spec states that I can use any delimiter, I've chosen to use newline.

Online demo

# Answer
> 6 votes
# Ruby 2.0, 41+1 characters

There, now it complies with the updated rules and makes prettier output.

```
gsub(/\w+/){$&.chars.map{|c|c.ord&31}*?-}

```

Run with `-p` switch:

```
ruby -p ord.rb <<< "ABC! Defghi, jklmnopqr stuvwxyz"
1-2-3! 4-5-6-7-8-9, 10-11-12-13-14-15-16-17-18 19-20-21-22-23-24-25-26

```

# Answer
> 5 votes
# Perl: ~~42~~ 38 characters

```
s/\S(?=\S)/$&-/g;s/[a-z]/31&ord$&/ige

```

Sample run:

```
bash-4.1$ perl -pe 's/\S(?=\S)/$&-/g;s/[a-z]/31&ord$&/ige' <<< "Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given."
8-5-18-5-'-19 1-14-15-20-8-5-18 5-24-1-13-16-12-5-, 9 8-15-16-5 20-8-1-20 20-8-9-19 23-9-12-12 9-12-12-21-19-20-18-1-20-5 13-25 16-15-9-14-20-! 9-6 9-20-'-19 21-14-1-2-12-5-, 13-15-18-5 19-16-5-3-19 23-9-12-12 2-5 7-9-22-5-14-.

```

# Answer
> 5 votes
### GolfScript, 37 36 23 characters

The following version takes newline as delimiter (as Peter's solution):

```
{.32|96^:@`]@27,?0>=n}%

```

A version which interprets words and delimiters as in the examples given is 36 characters long:

```
' '/{'-'*{.32|96^:@`]@27,?0>=}%' '}%

```

(Strange enough my first version `'-'*'- -'/' '*{.32|96^:@`@0>@27<&if}%` didn't work...)

Takes input on STDIN. The example can be tested online:

```
> 'Hello world!'
8-5-12-12-15 23-15-18-12-4-!

```

# Answer
> 3 votes
## R - 134 characters

A bit too long to be really in competition but here we go:

```
s=sapply
l=letters
cat(s(strsplit(scan(,""),""),function(x)paste(s(tolower(x),function(y)ifelse(y%in%l,which(l==y),y)),collapse="-")))

```

Word delimiter is space, character delimiter is `-`.

# Answer
> 2 votes
## Tcl, 82

```
lmap a [split [string tol $i] {}] {expr {[string is alpha $a]?[scan $a %c]-96:$a}}

```

Because you did not specify what you want, well, here an expression.
Input in `i`, result of the expression is the result.

Example:

```
% set i "Hello World!"
Hello World!
% lmap a [split [string tol $i] {}] {expr {[string is alpha $a]?[scan $a %c]-96:$a}}
8 5 12 12 15 { } 23 15 18 12 4 !

```

Word delimiter is `{ }`, character delimiter is

# Answer
> 2 votes
## Python - 47 ~~63~~

This assumes you've assigned the string to the variable `s`.

47 uses a flagrant abuse of the rules and says that `[` is the delimiter for the start of the original string, `]` marks the end of the original string, `,` marks the different characters and unchanged characters are captured in quotes.

```
str([(x,ord(x)-64)[x.isalpha()] for x in s.upper()])

```

Alternatively, 62 squeezes a line from below (although `'A'<=x<='Z'` is just as long and works just as well.:

```
'-'.join([str((x,ord(x)-64)[x.isalpha()]) for x in s.upper()])

```

63:

```
'-'.join([str((x,ord(x)-64)[64<ord(x)<91]) for x in s.upper()])

```

And the sample output:

```
>>> s = "Hello World!"
>>> '-'.join([str((x,ord(x)-64)[64<ord(x)<91]) for x in s.upper()])
'8-5-12-12-15- -23-15-18-12-4-!'

```

# Answer
> 2 votes
**Javascript, ~~81~~ 74**

~~`""+[].map.call(prompt(),function(c){a=c.charCodeAt(0);return a>65&&a<123?a&31:c})`~~

With the input taken from a variable
`""+[].map.call(s,function(c){a=c.charCodeAt(0);return a>65&&a<123?a&31:c})`

Output from the string you chose

> 8,5,18,5,',19, ,1,14,15,20,8,5,18, ,5,24,1,13,16,12,5,,, ,9, ,8,15,16,5, ,20,8,1,20, ,20,8,9,19, ,23,9,12,12, ,9,12,12,21,19,20,18,1,20,5, ,13,25, ,16,15,9,14,20,!, ,9,6, ,9,20,',19, ,21,14,1,2,12,5,,, ,13,15,18,5, ,19,16,5,3,19, ,23,9,12,12, ,2,5, ,7,9,22,5,14,.

```
          |  Word  |  Char  |
Delimiters|  , ,   |    ,   |

```

# Answer
> 2 votes
# Mathematica 68

Commas used as separators.

```
If[64 < # < 97, # - 64, FromCharacterCode@#] & /@ ToCharacterCode@ToUpperCase@i

```

**Example**

```
i="To be, or not to be,--that is the question:-- Whether 'tis nobler in
the mind to suffer The slings and arrows of outrageous fortune Or to
take arms against a sea of troubles, And by opposing end them?";

If[64 < # < 97, # - 64, FromCharacterCode@#] & /@ ToCharacterCode@ToUpperCase@i

```

> {20, 15, " ", 2, 5, ",", " ", 15, 18, " ", 14, 15, 20, " ", 20, 15, " ", 2, 5, ",", "-", "-", 20, 8, 1, 20, " ", 9, 19, " ", 20, 8, 5, " ", 17, 21, 5, 19, 20, 9, 15, 14, ":", "-", "-", " ", 23, 8, 5, 20, 8, 5, 18, " ", "'", 20, 9, 19, " ", 14, 15, 2, 12, 5, 18, " ", 9, 14, " ", 20, 8, 5, " ", 13, 9, 14, 4, " ", 20, 15, " ", 19, 21, 6, 6, 5, 18, " ", 20, 8, 5, " ", 19, 12, 9, 14, 7, 19, " ", 1, 14, 4, " ", 1, 18, 18, 15, 23, 19, " ", 15, 6, " ", 15, 21, 20, 18, 1, 7, 5, 15, 21, 19, " ", 6, 15, 18, 20, 21, 14, 5, " ", 15, 18, " ", 20, 15, " ", 20, 1, 11, 5, " ", 1, 18, 13, 19, " ", 1, 7, 1, 9, 14, 19, 20, " ", 1, " ", 19, 5, 1, " ", 15, 6, " ", 20, 18, 15, 21, 2, 12, 5, 19, ",", " ", 1, 14, 4, " ", 2, 25, " ", 15, 16, 16, 15, 19, 9, 14, 7, " ", 5, 14, 4, " ", 20, 8, 5, 13, "?"}

# Answer
> 2 votes
## C# - 137 Characters

This code assumes the string to convert is the **s** variable

```
Regex.Replace(Regex.Replace(s.ToUpper(),@"[A-Z]",m=>(((int)m.Value[0])-64).ToString()+'-'),@"[^\w\s-]",m=>m.Value+'-').Replace("- "," ");

```

# Answer
> 2 votes
# Jelly, 11 bytes

```
26R;`,@ØẠyK

```

Try it online!

Uses space as a delimiter.

## How it works

```
26R;`,@ØẠyK - Main link. Takes a string s on the left
26R         - Yield [1, 2, ..., 26]
   ;`       - Concatenate it to itself; [1, 2, ..., 26, 1, 2, ..., 26]
       ØẠ   - Yield "ABC...XYZabc...xyz"
     ,@     - Pair; [["A", "B", ..., "Z", "a", ..., "z"], [1, 2, ..., 26, 1, ..., 26]]
         y  - Transliterate s according to the mapping above
          K - Join by spaces

```

# Answer
> 1 votes
# Q, 53

```
{1_ssr[-3!(`$'x)^`$(.Q.a!($)1+(!)26)@(_)x;"``";"  "]}

```

Backtick Delimited

```
q){1_ssr[-3!(`$'x)^`$(.Q.a!($)1+(!)26)@(_)x;"``";"  "]}"Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given."
"8`5`18`5`'`19  1`14`15`20`8`5`18  5`24`1`13`16`12`5`,  9  8`15`16`5  20`8`1`20  20`8`9`19  23`9`12`12  9`12`12`21`19`20`18`1`20`5  13`25  16`15`9`14`20`!  9`6  9`20`'`19  21`14`1`2`12`5`,  13`15`18`5  19`16`5`3`19  23`9`12`12  2`5  7`9`22`5`14`."

```

# Answer
> 1 votes
# Japt v2.0a0 `-S`, 10 bytes

```
¬®r\lÈc uH

```

Try it

```
¬®r\lÈc uH     :Implicit input of string
¬              :Split
 ®             :Map
  r            :  Replace
   \l          :  /[A-Z]/gi
     È         :  Pass each match through a function
      c        :    Character code
        u      :    Modulo
         H     :    32

```

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


# Question
Title: My array should equal this, but it doesn't!
Given an array of integers **`a`** which contains *n* integers, and a single integer **`x`**; remove the fewest amount of elements from **`a`** to make the sum of **`a`** equal to **`x`**. If no combinations of **`a`** can form **`x`**, return a falsy value.

As pointed out in a comment this is the maximum set with a sum of **x**, excuse my lesser math brain. I forgot a lot of terms since college.

---

**Examples (Truthy):**

`f([1,2,3,4,5,6,7,8,9,10], 10) = [1,2,3,4]`

`f([2,2,2,2,2,2,2,2,2], 10) = [2,2,2,2,2]`

`f([2,2,2,2,-2,-2,-2,-4,-2], -8) = [2,2,-2,-2,-2,-4,-2]`

`f([-2,-4,-2], -6) = [-4,-2] OR [-2,-4]`

`f([2,2,2,4,2,-2,-2,-2,-4,-2], 0) = [2,2,2,4,2,-2,-2,-2,-4,-2]` (Unchanged)

`f([], 0) = []` (Unchanged Zero-sum Case)

---

**Examples (Falsy, any consistent non-array value):**

**Impossible to Make Case:** `f([-2,4,6,-8], 3) = falsy (E.G. -1)`

**Zero Sum Case:** `f([], non-zero number) = falsy (E.G. -1)`

* *Note: any value like `[-1]` cannot be valid for falsy, as it is a potential truthy output.*

---

Rules:

* Input may be taken in array form, or as a list of arguments, the last or first being `x`.
* Output may be any delimited list of integers. E.G. `1\n2\n3\n` or `[1,2,3]`.
* Any value can be used as a falsy indicator, other than an array of integers.
* Your code must maximize the size of the end array, order does not matter.
    + E.G. For `f([3,2,3],5)` both `[2,3]` and `[3,2]` are equally valid.
    + E.G. For `f([1,1,2],2)` you can only return `[1,1]` as `[2]` is shorter.
* Both the sum of **`a`** and the value of **`x`** will be less than `2^32-1` and greater than `-2^32-1`.
* This is , lowest byte-count wins.
* If there are multiple subarrays of the same size that are valid, it is *not* acceptable to output all of them. You must choose a single one and output that one.

---

Let me know if this has been posted, I couldn't find it.

Posts I found *like this*: Related but closed, ...

# Answer
> 7 votes
# Brachylog, 8 bytes

```
h⊇.+~t?∧

```

Try it online!

Monthly Brachylog answer. Returns `false.` if it is not possible.

### Explanation

```
h⊇.           The output is a subset of the head of the input
  .+~t?       The sum of the elements of the output must equal the tail of the input
       ∧      (Avoid implicit unification between the output and the input)

```

# Answer
> 6 votes
# Python 2, ~~108~~ 104 bytes

```
lambda a,n:[x for l in range(len(a)+1)for x in combinations(a,l)if sum(x)==n][-1]
from itertools import*

```

Try it online!

-4 bytes, thanks to Jonathan Allan

---

# Python 2, ~~108~~ 106 bytes

```
def f(a,n):
 q=[a]
 while q:
  x=q.pop(0);q+=[x[:i]+x[i+1:]for i in range(len(x))]
  if sum(x)==n:return x

```

Try it online!

-2 bytes, thanks to Janathan Frech

# Answer
> 5 votes
# 05AB1E, 9 bytes

```
æʒOQ}0ªéθ

```

Try it online!

# Answer
> 4 votes
# Japt `-h`, 11 bytes

```
à f_x ¥VÃñl

```

Try it online!

# Answer
> 4 votes
# Pyth, 8 bytes

* **8-byter** (Try it!) – Outputs only one possible solution. For unsolvable inputs, it doesn't print anything to STDOUT, which is an empty string, which is technically speaking falsey in Pyth, but writes to STDERR. Thanks to FryAmTheEggman for suggesting this (ignoring STDERR and focusing on the STDOUT output only), thus saving 1 byte.

```
efqz`sTy

```
* **9-byter** (Try it!) – Outputs only one possible solution, wrapped in a singleton list as allowed by default (e.g. `([1...10], 10) -> [[1,2,3,4]]; ([], 0) -> [[]]`). For unsolvable inputs, it returns `[]`, which is falsey in Pyth.

```
>1fqz`sTy

```
* **10-byter** (Try it!) – For a clearer output, without using the singleton-list rule and using `0` rather than `[]` as a falsy value.

```
e+0fqz`sTy

```

### Explanation

First, the code computes the powerset of the input list (all possible ordered sub-collections thereof). Then, it only keeps those collections whose sum is equal to the input number. It should be noted that the collections are generated from the shortest to the longest, so we focus on the last one. To obtain it:

* The **8-byter** simply uses the *end* built-in, which throws an error, but STDERR can be ignored as per our site rules, the output to STDOUT being an empty string, which is falsy.
* The **9-byter** takes the last element, but using the equivalent Python code `lst[-1:]` in place of `lst[-1]` to avoid errors from being thrown for unsolvable inputs.
* The **10-byter** prepends a **0** to the list of filtered sub-collections, then takes the end of that collection (last element). If the inputs aren't solvable, then **0** is naturally used instead.

# Answer
> 3 votes
# Jelly, 7 bytes

```
ŒPS⁼¥ƇṪ

```

Try it online!

Output clarified over TIO.

# Answer
> 3 votes
# Perl 6, ~~38~~ 37 bytes

```
{*.combinations.grep(*.sum==$_).tail}

```

Try it online!

Curried function.

# Answer
> 3 votes
# Brachylog, 4 bytes

```
⟨⊇+⟩

```

Try it online!

Just about equivalent to Fatalize's `h⊇.+~t?∧`, except a **lot** shorter, thanks to the *predicate composition* feature which according to the edit history of the reference was a work in progress until January 8, postdating the answer by over two months. `⟨⊇+⟩` is a *sandwich*, expanding to `{[I,J]∧I⊇.+J∧}`, where the braces are in this case irrelevant as the sandwich is on its own line anyhow.

```
                The input
[I,J]           is a list of two elements I and J.
        .       The output,
         +J     which sums to J
           ∧    (which we don't unify with the output),
      I⊇        is a sublist of I
     ∧          (which we don't unify with [I,J]).

```

A far less dramatic transformation of Fatalize's answer, which uses the same predicates with the same variables but comes out a byte shorter from being organized differently:

# Brachylog, 7 bytes

```
h⊇.&t~+

```

Try it online!

```
           The input
h          's first element
 ⊇         is a superlist of
  .        the output,
   &       and the input
    t      's last item
     ~+    is the sum of the elements of
           the output.

```

(Also, if anyone wants to see something odd, change any of the underscores in the test cases into hyphens.)

# Answer
> 2 votes
# , ~~100~~ 80 bytes

```
function(a,x){i[sum(a|1):0,j[combn(a,i,,F),if(sum(j)==x)return(j)]]
F}
`[`=`for`

```

Try it online!

*20 bytes saved thanks to digEmAll*

Returns `FALSE` for impossible criteria.

# Answer
> 2 votes
# Pyth, 14 bytes

```
A.Q|>1fqsTHyG0

```

Try it online!

# Answer
> 2 votes
This started out cool and small, but edge cases got me. Whatever happens, I'm proud of the work I put into this.

# Python 3, ~~169 161~~ 154 bytes

```
from itertools import*
def f(a,x):
	if sum(a)==x:return a
	try:return[c for i in range(len(a))for c in combinations(a,i)if sum(c)==x][-1]
	except:return 0

```

Try it online!

# Answer
> 2 votes
# Clean, 89 bytes

```
import StdEnv,Data.List,Data.Func
$n=find((==)n o sum)o sortBy(on(>)length)o subsequences

```

Try it online!

Defines the function `$ :: Int -> [Int] -> (Maybe [Int])` returning `Nothing` if there is no appropriate combination of elements, and `(Just [elements...])` otherwise.

# Answer
> 2 votes
# JavaScript (ES6), 108 bytes

Takes input as `(array)(n)`. Returns either an array or `false`.

```
a=>n=>a.reduce((a,x)=>[...a,...a.map(y=>1/r[(y=[...y]).push(x)]||eval(y.join`+`)-n?y:r=y)],[[]],r=!n&&[])&&r

```

Try it online!

# Answer
> 1 votes
# Attache, 28 bytes

```
${(y&`=@Sum\Radiations@x)@0}

```

Try it online!

## Alternatives

**34 bytes**: `f[x,y]:=({y=Sum@_}\Radiations@x)@0`

**30 bytes**: `First@${y&`=@Sum\Radiations@x}`

**29 bytes**: `{(_&`=@Sum\_2)@0}#/Radiations`

**29 bytes**: `${({y=Sum@_}\Radiations@x)@0}`

**29 bytes**: ``@&0@${y&`=@Sum\Radiations@x}`

**29 bytes**: `{_}@@${y&`=@Sum\Radiations@x}`

## Explanation

```
${(y&`=@Sum\Radiations@x)@0}
${                         }    function receiving two arguments, x and y
            Radiations@x        calculate the radiations of x
                                (simulates removing all possible subslices of x)
           \                    keep those radiations
        Sum                     ...whose sum...
     `=@                        ...equals...
   y&                           ...y
  (                     )@0     select the first one (always the longest)

```

# Answer
> 0 votes
# APL(NARS), 65 chars, 130 bytes

```
{m←⍺=+/¨v←1↓{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}⍵⋄0=↑⍴b←m/v:⍬⋄b⊃⍨n⍳⌈/n←⍴¨b}

```

↓ is used because the first element of the set of sets would be one void set (here ⍬ Zilde), that one want eliminate because it seems +/⍬ is zero...

For not find, or error it would return ⍬ or in print text:

```
  o←⎕fmt
  o ⍬
┌0─┐
│ 0│
└~─┘

```

test:

```
  z←{m←⍺=+/¨v←1↓{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}⍵⋄0=↑⍴b←m/v:⍬⋄b⊃⍨n⍳⌈/n←⍴¨b}

  o 1 z ,1
┌1─┐
│ 1│
└~─┘
  o 2 z ,1
┌0─┐
│ 0│
└~─┘
  o 10 z 1 2 3 4 5 6 7 8 9 10
┌4───────┐
│ 1 2 3 4│
└~───────┘
  o 10 z 2,2,2,2,2,2,2,2,2
┌5─────────┐
│ 2 2 2 2 2│
└~─────────┘
  o ¯8 z 2,2,2,2,¯2,¯2,¯2,¯4,¯2
┌7──────────────────┐
│ 2 2 ¯2 ¯2 ¯2 ¯4 ¯2│
└~──────────────────┘
  o ¯6 z ¯2,¯4,¯2
┌2─────┐
│ ¯4 ¯2│
└~─────┘
  o 0 z 2,2,2,4,2,¯2,¯2,¯2,¯4,¯2
┌10───────────────────────┐
│ 2 2 2 4 2 ¯2 ¯2 ¯2 ¯4 ¯2│
└~────────────────────────┘
  o 10 z 1 2 3 4
┌4───────┐
│ 1 2 3 4│
└~───────┘
  o 10 z 1 2 3
┌0─┐
│ 0│
└~─┘
  o 0 z ⍬
┌0─┐
│ 0│
└~─┘
  o +/⍬
0
~

```

# Answer
> 0 votes
# Husk, 8 bytes

```
▲fo=⁰ΣQ²

```

Try it online!

Brachylog is **insane.**

# Answer
> 0 votes
# Haskell, 68 bytes

```
import Data.List
f x=find((==x).sum).sortOn(sum.(-1<$)).subsequences

```

Try it online!

Defines `f x a` to return `Just` a subset or `Nothing`.

The only trick here is that `sum.(-1<$)` is one byte shorter than `(0-).length`.

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