title: Binary to Hexadecimal

text:
# Question
Title: Binary to Hexadecimal
Convert a binary number (of any size) into a hexadecimal number.

**Input**
A *POSITIVE* binary number with just the `0`s and `1`s. A valid input will always match the following regex: `[0-1]+`. If the input is *not* a valid binary number, that is, anything not matching this regex, the output should be `0` or the program should exit, or error. The output does not need the leading `0x` nor does it need to be capitalized.

**Output**
The binary number converted to hexadecimal.

**Winning**
Original Code-Golf Rules, Lowest amount of bytes.

**Examples**

```
IN: [101]
OUT: [0x5] OR [5]

IN: [10000000010100100000]
OUT: [0x80520] OR [80520]

IN: [1010101]
OUT: [0x55] OR [55]

IN: [1111111111111111]
OUT: [0xFFFF] OR [FFFF] OR [0xffff] OR [ffff]

IN: [1012101]
OUT: [0]

IN: [a]
OUT: [0]

IN: [-1010101]
OUT: [0]

IN: [abcdef]
OUT: [0]

IN: [2]
OUT: [0]

```

# Answer
# MY, ~~8~~ ~~6~~ 5 bytes

```
⍞PrH↵

```

Try it online!

## How?

* line of raw input
* `P` basify
* `r` convert from binary
* `H` convert to hex
* output

Errors if input isn't correct.
> 3 votes

# Answer
# Java, 126 119 117 110 104 Bytes

### Thanks to Jakob and Zacharý

```
class A{public static void main(String[]s){System.out.print(Long.toHexString(Long.parseLong(s[0],2)));}}

```

Expanded:

```
class A
{
    public static void main(String[] s)
    {
        System.out.print(Long.toHexString(Long.parseLong(s[0], 2)));
    }
}

```
> 1 votes

# Answer
# PHP, 25+1 bytes

```
<?=dechex(bindec($argn));

```

Run as pipe with `-F`.

or 27+1 bytes: (`-R`)

```
printf("%x",bindec($argn));

```

or 28+1 bytes: (`-F`)

```
<?=base_convert($argn,2,16);

```

or 30+1 bytes: (`-R`)

```
eval("printf('%x',0b$argn);");

```
> 1 votes

# Answer
# Retina, ~~72~~ 70 bytes

```
A`[^01]
T`d`l`.(?!(....)*$)
T`d`23`b\d
T`d`4-7`b.\d
T`d`89L`b..\d
a|b

```

Try it online! Output is blank on error. Edit: Saved 2 bytes thanks to @PunPun1000. Explanation:

```
A`[^01]

```

Delete non-binary input.

```
T`d`l`.(?!(....)*$)

```

Convert all digits not in the correct position to `a`s and `b`s instead.

```
T`d`23`b\d

```

Add 2 to digits that follow a `b`.

```
T`d`4-7`b.\d

```

Add 4 to digits two after a `b`.

```
T`d`89L`b..\d

```

Add 8 to digits three after a `b`.

```
a|b

```

The `a`s and `b`s have done their job and can be deleted.
> 1 votes

# Answer
# C, 168 bytes

```
i,l,k,n;f(char*s){char*o=malloc(l=strlen(s));for(i=n=0;i<l;n+=k<<i++)if((k=s[l-i-1]-48)&&k-1)return 0;for(i=o[--l]=0;n;n/=16)k=n%16,o[l-++i]=k>9?k+55:k+48;puts(o+l-i);}

```

Try it online!

**Unrolled:**

```
i,l,k,n;
f(char *s)
{
    // Allocate a string for the hexadecimal digits.
    // The number of digits in the hex number is
    // sure to be less or equal to that of binary.
    char *o = malloc(l=strlen(s));

    // Convert binary to decimal.
    // The function returns zero without printing
    // anything if there are extraneous characters.
    for (i=n=0; i<l; n+=k<<i++)
        if ((k=s[l-i-1]-48) && k-1) return 0;

    // Convert decimal to hexadecimal.
    for (i=o[--l]=0; n; n/=16)
        k = n%16, o[l-++i] = k>9 ? k+55 : k+48;

    // Print the number in hexadecimal.
    puts(o+l-i);
}

```
> 1 votes

# Answer
# CJam, 17 bytes

```
{2bGb{_9>'70?+}%}

```

Function that takes an array of bits as input.

Test Version

```
{
2b     e# Convert from base-2 to base-10.
Gb     e# Convert from base-10 to base-16.
{      e# For each digit in the hex version...
_      e# Duplicate it.
9>     e# Check if it's greater than 9.
'70?   e# If it is, add a '7' (char) to the stack. If not, add a 0 (int).
 +     e# Add the new item to the digit. Int + char => Increment char's ASCII value by int. (e.g '7' + 10 = 'A')
}%
}

```

If necessary, here's a version that checks for invalid input (**29 bytes**):

```
{_2,|$2,=1W?*2bGb{_9>'70?+}%}

```

Test Version

It outputs 0 for an empty array and throws an exception for all other invalid input.

How validation works....

```
{
_2,|$  e# Get Logical OR of input array and [0,1], sorted.
2,=    e# Does that equal [0,1]?
1W?    e# If the arrays are equal add 1 to the stack, if not add -1.
*      e# Repeat the input as many times as the number just added to the stack.
       e# If the number is 1, the input is unchanged.
       e# If it's -1 you get an error for an invalid number of repetitions.
...

```
> 1 votes

# Answer
# 6502 machine code (C64), 100 bytes

```
00 C0 20 FD AE 20 9E AD 20 A3 B6 8D 1C C0 A0 00 84 FB 84 FC 29 03 AA D0 16 A2
04 A4 FB C0 FF D0 0E A4 FC A9 00 99 62 C0 A0 C0 A9 62 4C 1E AB A9 00 85 FE CA
30 1B 06 FE A4 FB E6 FB B1 22 C9 30 F0 F1 C9 31 F0 03 4C 99 AD A5 FE 09 01 85
FE D0 E2 A9 30 05 FE C9 3A 30 02 69 06 A4 FC 99 62 C0 E6 FC D0 B5

```

### Online demo

Usage: `sys49152,"[input]"`, where `[input]` is your binary string, e.g. `sys49152,"10000000010100100000"`.

**Important:** When the program was loaded from disk (like in the online demo!), **issue a `new` command first**! This is because loading the program fiddles with some BASIC pointers and the machine thinks there's no RAM left for a string...

---

**Explanation** (commented disassembly listing):

```
00 C0       .WORD $C000         ; load address
20 FD AE    JSR $AEFD           ; check for comma
20 9E AD    JSR $AD9E           ; evaluate expression
20 A3 B6    JSR $B6A3           ; get string from expression
8D 1C C0    STA $C01C           ; store input string length for CPY instruction
A0 00       LDY #$00            ; initialize counters to 0:
84 FB       STY $FB             ;    read counter
84 FC       STY $FC             ;    write counter
29 03       AND #$03            ; number of bits in first incomplete nibble
AA          TAX                 ;  -> to X register
D0 16       BNE .nibble         ; branch to nibble decoding if not 0
 .mainloop:
A2 04       LDX #$04            ; from here on 4 bits per nibble
A4 FB       LDY $FB             ; load read counter to Y
C0 04       CPY #$FF            ; compare with input length (argument modified)
D0 0E       BNE .nibble         ; not yet done -> branch to nibble decoding
A4 FC       LDY $FC             ; load store counter
A9 00       LDA #$00            ; write NUL terminator
99 62 C0    STA .outbuf,Y       ; to output string
A0 C0       LDY #$C0            ; load address of
A9 62       LDA #$62            ; output string
4C 1E AB    JMP $AB1E           ; and jump to string output routine
 .nibble:
A9 00       LDA #$00            ; initialize value of nibble to zero
85 FE       STA $FE             ; store to temporary variable
 .nibbleloop:
CA          DEX                 ; decrement number of bits
30 1B       BMI .nibbleout      ; no bits left -> prepare for output
06 FE       ASL $FE             ; shift temporary variable left
A4 FB       LDY $FB             ; load read counter to Y
E6 FB       INC $FB             ; increment read counter
B1 22       LDA ($22),Y         ; load next input character
C9 30       CMP #$30            ; compare with '0'
F0 F1       BEQ .nibbleloop     ; if equal, handle next bit
C9 31       CMP #$31            ; compare with '1'
F0 03       BEQ .nibbleadd      ; if equal, add that bit
4C 99 AD    JMP $AD99           ; neither '0' or '1' -> type mismatch error
 .nibbleadd:
A5 FE       LDA $FE             ; load temporary variable
09 01       ORA #$01            ; set lowest bit
85 FE       STA $FE             ; store temporary variable
D0 E2       BNE .nibbleloop     ; handle next bit
 .nibbleout:
A9 30       LDA #$30            ; load character '0'
05 FE       ORA $FE             ; combine with value from temporary variable
C9 3A       CMP #$3A            ; result smaller than 0x39 ('9') ?
30 02       BMI .nibblestore    ; then store that
69 06       ADC #$06            ; otherwise add offset to get in range 'a'-'f'
 .nibblestore:
A4 FC       LDY $FC             ; load write counter
99 62 C0    STA .outbuf,Y       ; write to output string
E6 FC       INC $FC             ; increment write counter
D0 B5       BNE .mainloop       ; back to main loop
 .outbuf:                       ; "BSS", output string is stored from here

```

**Remarks:**

* Input validation is fully implemented (and takes quite a few bytes, otherwise it would be possible to directly output each decoded nibble without temporary storage)
* I took the liberty to interpret "*any length*" as "*any length my C64 system can read from a command line as a string*", which is quite limited ... 69, or if you abbreviate `sys` with `sY` 70 "bits", because the whole command line is limited to 80 characters ... hope this is acceptable :)
> 1 votes

# Answer
# , 34 bytes

```
function(x)as.hexmode(strtoi(x,2))

```

Returns `NA` for invalid input.

Try it online!
> 1 votes

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

```
CbQ*Ch

```

Try it online!
Error case

It's my first try ever to a Code Golf, advices welcomed!
Handles error cases \o/

The idea is to make the conversion from base 2 to base 10, and back to base 2. Compare the result with the initial input, if it's not the same, then the conversion have failed.

```
1012101 => 0
a => empty
-1010101 => 0
abcdef => empty
2 => 0

```

### Explanation

```
CbQ*Ch
C  # convert input from base 2 to base 10
 b # ...and back to 2
  Q # 1 if the full conversion back and return equals the input, else 0
   * # multiply to get 0 if error case
    C # convert corrected input from base 2 to base 10
     h # convert it to base 16

```
> 1 votes

# Answer
# Ruby, 27 25 bytes

```
->b{'%x'%Integer('0b'+b)}

```

Try it online!

-2 bytes thanks to histocrat.

Inputs and outputs strings.

String#to\_i vows to never throw an exception, returning `0` for many invalid inputs. That would be fine, except for this property:

`Extraneous characters past the end of a valid number are ignored.`

Meaning that `1012101` is read up to the 2 and interpreted as `101` (or 5), which is no good. We can use the stricter `Integer()` instead, which throws an exception for any number that is not binary. It lets through negative numbers, so we need to invalidate those by prepending `0b` to the input. `0` as input returns `0`, which is within the specification.
> 1 votes

# Answer
# Tcl, 66 bytes

```
proc H b {expr {[regexp ^\[01\]+$ $b]?[format %x [scan $b %b]]:0}}

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~52~~ ~~29~~ 26 bytes

```
print(hex(int(input(),2)))

```
> 0 votes

# Answer
# Rust, ~~58~~ 57 bytes

Saved one byte using 8 bit int

```
|n:&str|format!("{:x}",u8::from_str_radix(n,2).unwrap());

```

Ungolfed

```
fn main() {
    let bin = "101";
    println!("{:x}", u8::from_str_radix(bin, 2).unwrap()); // 5
}

```

Try it online!
> 0 votes

# Answer
# Kotlin 1.1, 92 bytes

## Submission

```
fun r(i:String):String{return if(i.matches(Regex("[01]+")))i.toLong(2).toString(16)else "0"}

```

## Beautified

```
fun r(i: String): String {
    return if (i.matches(Regex("[01]+"))) {    // If it is valid
        i.toLong(2)                            // Convert to Long
         .toString(16)                         // Return as hex
    } else {                                   // Otherwise
        "0"                                    // Return 0
    }
}

```

## Explanation

* The number is checked to be valid by the regex
* Kotlin to and from string methods are used to convert the string

**Unfortunately this does not run on TryItOnline, as it uses newer Kotlin features**
> 0 votes

# Answer
# Stacked, 24 bytes

```
[:\'1|0'-#'0=\unbin*hex]

```

Try it online!
> 0 votes

# Answer
## Dyvil, 32 Bytes

```
s=>Int.parseInt(s,2).toHexString

```

Pretty much self-explanatory. Throws a `NumberFormatException` for invalid inputs. Output without `0x`.
> 0 votes

# Answer
# Javascript (ES6) ~~50~~ ~~45~~ 39 bytes

```
h=
s=>isNaN(n=+('0b'+s))?0:n.toString(16)
```

```
<input id="i" type="text" onchange="o.innerHTML=h(i.value)"><pre id="o"></pre">
```

with thanks to Shaggy 6 bytes less. Or for a 26 byte version that returns 'NaN' instead of '0' on error:

```
s=>+('0b'+s).toString(16)

```

`'0b'` was introduced as a binary number prefix in ES6.
> 0 votes

# Answer
# Python 2, 27 bytes

```
lambda s:hex(int('0b'+s,2))

```

Try it online!

We invalidate inputs like `0b1010` or `-1010` by prefixing `0b` ourselves — because `0b0b1010` and `0b-1010` are invalid base 2 literals in Python.
> 0 votes

# Answer
# Perl 6, 19 bytes ( = 18 + 1 for "-p" )

`perl6 -pe '$_=:2($_).base: 16'`

Nothing creative. The `:2(string)` construct takes the `string` and interprets it as a number in base 2. (This works for arbitrary bases up to base 36.) The `base` method takes a number and gives a string representation in the given base.

Due to `-p`, it loads one line from stdin at a time, expecting each to contain one number. If you feed it something that's not valid binary number, you get an error and the program ends.
> 0 votes

# Answer
# Lua, ~~43~~ 40 bytes

```
print(("").format("%x",tonumber(...,2)))

```

I think it explains itself. Parses from base 2 to decimal then formats it to hex. If it is not binary input it will simply error (tested with Lua 5.2,5.3).
> 0 votes

# Answer
# Javascript, 28 bytes

```
x=>eval("0b"+x).toString(16)

```

`eval`s `x` with a `0b` in front of it, turning it into a binary literal. Binary literals error out on non binary values of `x`. `.toString(16)` turns `x` into a hexdecimal.
> 0 votes

# Answer
# Perl 5, 30 + 1 (`-n`) = 31 bytes

```
printf"%x",!y/01//c&&oct"0b$_"

```

Try it online!
> 0 votes

# Answer
## REXX, 15 bytes

```
say b2x(arg(1))

```
> 0 votes

# Answer
# Julia, 24 bytes

```
f(x)=hex(parse(Int,x,2))

```

Try it online!
> 0 votes

# Answer
# Common Lisp, 48 bytes

```
(format t"~X"(parse-integer(read-line):radix 2))

```

Try it online!
> 0 votes

# Answer
# Bash, 19 bytes

```
printf %x $((2#$1))

```

Try it online!
> 0 votes

# Answer
# \>\<\>, ~~84~~ 82 Bytes

Improved somewhat. Probably still improvable.

```
l&1>:}*{$}2\~-?\02.
~~&\?&:-1&*/1l+<
>:f1+%:}\
\?:,+1f-/.47r~
)a:;!?ln/?
.47o+*b5/

```

Old version:

```
1l&>:}*{$}2\
~~&\?&:-1&*/l +<
>:f1+%:}-f1\1-?/
\?      :,+/r~
n/?)a:;!?l <
5/.4co+*b

```

~~I'll work on improving it later, see if I can get rid of that big chunk of whitespace.~~

### How it works:

(This is for the old version, new version works the same but with loops in different positions)

Implicit input, assumed to be a series of bits such as '1,1,1,0,0', with the ones place on the right, as normal.

```
l&1

```

Store the length in the registry; push 1 to the stack. The 1 will record which place we are on in the binary number.

```
   >:}*{$}2\
   \?&:-1&*/

```

Replace each bit with the value it represents. For example, 1,1,1,0 goes to 8,4,2,0.

```
~~&

```

Delete the counter and position-measurer.

```
           /l +<
           \1-?/

```

Sum the stack. Results in the number that was represented in binary.

```
>:f1+%:}-f1\
\?      :,+/

```

Convert this to hexadecimal, which unfortunately reverses it and leaves a trailing 0. For example, 28 becomes 12, 1, 0.

```
           /r~

```

Remove the trailing zero and un-reverse it.

```
n/?)a:;!?l <
5/.4co+*b

```

This is all for printing. If the value is \<10, just print it normally. Otherwise, add 55 and print the ascii character of this number.
> 0 votes

# Answer
# \>\<\>, 50 bytes

```
{:?v~
!v0>}l4%?
 r
4<]nv?)9:+++*2}*4}*8[
+"W"<.33o

```

Try It Online

Complies with the question by erroring on invalid input, but as it always ends with an error anyway, this is a bit tongue in cheek.

### How It Works

```
{:?v~ Pops leading 0s
...

...
!v0>}l4%? Adds leading 0s until the length of the binary is divisible by 4
 r        And reverses the input
...

...                   Repeatedly take the last 4 digits of the binary
4<]nv?)9:+++*2}*4}*8[ Calculate the value of those digits and print the hexadecimal value
+"W"<.33o             If the value is above 9, print the appropriate letter

```
> 0 votes

---
Tags: code-golf, binary, hexadecimal
---


title: Program an Uncircularness Score

text:
# Question
Title: Program an Uncircularness Score
Your task is to program a mathematical function \\$s\\$, that takes a nonempty finite set \\$A\\$ of points in the 2D plane, and outputs an uncircularity score \\$s(A)\\$ that satisfies following properties:

1. *Positive Definiteness*: If there is a circle or a straight line that contains all points of \\$A\\$, then \\$s(A) = 0\\$. Otherwise \\$s(A) \> 0\\$
2. *Surjectivity:* It is surjective to the nonnegative real numbers, that means for every nonnegative real number \\$r\\$ there is a finite subset \\$A\\$ of the plane such that \\$s(A) = r\\$.
3. *Translation Invariance:* \\$s\\$ is translation invariant if \\$s(A) = s(A + v)\\$ for every vector \\$v\\$ and for all \\$A\\$.
4. *Scale Invariance:* \\$s\\$ is scale invariant, if \\$s(A) = s(tA)\\$ for every \\$t≠0\\$ and for all \\$A\\$.
5. *Continuity.* \\$s\\$ is said to be *continuous* if the function \\$f(p) := s(A ∪ \\{p\\})\\$ (mapping the a point `p` to a real number) is continuous using the standard absolute value on the real numbers, and the standard euclidean norm on the points of the plane.

Intuitively speaking this *uncircularness score* can be thought of as something similar to the correlation coefficient in linear regression.

### Details

Your function in theory has to work in the reals, but for the purpose of this challenge you can use floating point numbers as substitute. Please provide an explanation of your submission and an argument why those five properties hold. You can take two lists of coordinates or a list of tuples or similar formats as input. You can assume that no point in the input is repeated i.e. all points are unique.

# Answer
# Python 2 with numpy, 116 bytes

```
from numpy import*
def f(x,y):a=linalg.lstsq(hstack((x,y,ones_like(x))),(x*x+y*y)/2);return a[1]/sum((x-a[0][0])**4)

```

Takes x and y as 2d column vectors and returns an array containing the answer. Note that this will give an empty array for a perfectly straight line or with 3 or fewer points. I think lstsq gives no residuals if there's a perfect fit.

### Explanation

Essentially, this finds the circle of best fit and gets the squared residuals.

We want to minimize `(x - x_center)^2 + (y - y_center)^2 - R^2`. It looks nasty and nonlinear, but we can rewrite that as `x_center(-2x) + y_center(-2y) + stuff = x^2 + y^2`, where the `stuff` is still nasty and nonlinear in terms of `x_center`, `y_center`, and `R`, but we don't need to care about it. So we can just solve `[-2x -2y 1][x_center, y_center, stuff]^T = [x^2 + y^2]`.

We could then back out R if we really wanted, but that doesn't help us much here. Thankfully, the lstsq function can give us the residuals, which satisfies most of the conditions. Subtracting the center and scaling by `(R^2)^2 = R^4 ~ x^4` gives us translational and scale invariance.

1. This is positive definite because the squared residuals are nonnegative, and we're dividing by a square. It tends toward 0 for circles and lines because we're fitting a circle.
2. I'm fairly sure it's not surjective, but I can't get a good bound. If there is an upper bound, we can map \[0, bound) to the nonnegative reals (for example, with 1 / (bound - answer) - 1 / bound) for a few more bytes.
3. We subtract out the center, so it's translationally invariant.
4. We divide by x\**4, which removes the scale dependence.
5. It's composed of continuous functions, so it's continuous.
> 2 votes

# Answer
# Python, 124 bytes

```
lambda A:sum(r.imag**2/2**abs(r)for a in A for b in A for c in A for d in A if a!=d!=b!=c for r in[(a-c)*(b-d)/(a-d)/(b-c)])

```

Takes *A* as a sequence of complex numbers (`x + 1j*y`), and sums Im(*r*)2/2|*r*| for all complex cross-ratios *r* of four points in *A*.

### Properties

1. *Positive Definiteness.* All terms are nonnegative, and they’re all zero exactly when all the cross-ratios are real, which happens when the points are collinear or concyclic.
2. *Surjectivity.* Since the sum can be made arbitrarily large by adding many points, surjectivity will follow from continuity.
3. *Translation Invariance.* The cross-ratio is translation-invariant.
4. *Scale Invariance.* The cross-ratio is scale-invariant. (In fact, it’s invariant under all Möbius transformations.)
5. *Continuity.* The cross-ratio is a continuous map to the extended complex plane, and *r* ↦ Im(*r*)2/2|*r*| (with ∞ ↦ 0) is a continuous map from the extended complex plane to the reals.

(Note: A theoretically prettier map with the same properties is *r* ↦ (Im(*r*)/(*C* \+ |*r*|2))2, whose contour lines w.r.t. all four points of the cross-ratio are circular. If you actually need an uncircularness measure, you probably want that one.)
> 2 votes

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


title: Form a list using prime numbers

text:
# Question
Title: Form a list using prime numbers
You have been given N piles of coins. You have decided to divide each of those B1, B2, ..., BN piles among separate groups of people. The amount of people receiving coins has to be a prime number and the amount of money given to each person must be different in each pile.

Input: N, B1, B2, ..., BN (The amount of coins in each individual pile).

Output: NP1, NP2, ..., NPN with NP being the number of people(prime number) receiving the coins. If this is impossible then yield some unachievable result (like `0`, `-1`, `None`, `[]`, or `"impossible"`) or raise an error.

Example:

```
3
7 8 9

```

Output: `7 2 3`

Because 7 is the only prime number that can divide 7 evenly, the same for 8 and 2 and 9 and 3. Also, notice that (7 / 7 = 1) ≠ (8 / 2 = 4) ≠ (9 / 3 = 3).

# Answer
# 05AB1E, 13 bytes

```
Ò.»â€˜ʒ÷DÙQ}θ

```

**Try it online!**

A port of my Pyth answer.

* `Ò` gets the prime fact**Ò**rs of each.
* folds a dyadic command, `â` (c**â**rtesi**â**n product) between each two elements in the list from right to left with opposite right/left operands.
* `€˜` flattens ach.
* `ʒ...}` filt**ʒ**rs those which satisfy the following condition:
    + `÷` pairwise integer division with the input.
    + `D` **D**uplicate (pushes two copies of the item to the stack).
    + `Ù` removes duplicate elements, keeping a **Ù**niq**Ù**e occurrence of each element.
    + `Q` checks for e**Q**uality.
* `θ` gets the last element.
> 5 votes

# Answer
# Jelly,  ~~15~~  14 bytes

```
³:ŒQẠ
ÆfŒpÇÐfṪ

```

A full-program which accepts one argument, a list of numbers, and prints a representation of another list of numbers, or `0` if the task is impossible.

**Try it online!**

### How?

```
³:ŒQẠ - Link 1, unique after division?: list of primes, Ps   e.g. [7,2,2]  or  [7,3,3]
³     - program's first input                                e.g. [7,8,8]  or  [7,9,30]
 :    - integer division by Ps                                    [1,4,4]      [1,3,10]
  ŒQ  - distinct sieve                                            [1,1,0]      [1,1,1]
    Ạ - all truthy?                                               0            1

ÆfŒpÇÐfṪ - Main link: list of coin stack sizes, Bs   e.g. [7,8,12]
Æf       - prime factorisation (vectorises)               [[7],[2,2,2],[2,2,3]]
  Œp     - Cartesian product                              [[7,2,2],[7,2,2],[7,2,3],[7,2,2],[7,2,2],[7,2,3],[7,2,2],[7,2,2],[7,2,3]]
     Ðf  - filter keep if:
    Ç    -   call last link (1) as a monad                 1       1       0       1       1       0       1       1       0
         -                                                [[7,2,2],[7,2,2],[7,2,2],[7,2,2],[7,2,2],[7,2,2]]
       Ṫ - tail (note: tailing an empty list yields 0)    [7,2,2]
         - implicit print

```
> 4 votes

# Answer
# Pyth, 15 bytes

```
ef{I/VQT.nM*FPM

```

**Try it here!**

### How?

```
ef{I/VQT.nM*FPM | Full program, which foregoes the size.
                |
             PM | Prime factorisation of each integer.
           *F   | Fold Cartesian Product over the list of primes.
        .nM     | Flatten each.
 f              | Filter.
  {I/VQT        | Filter condition (uses a variable T).
    /V          | Vectorised integer division...
      QT        | Over the input and the current item.
  {I            | Is invariant over deduplication (removing duplicates)?
e               | Take the last element.
                | Output the result implicitly.

```
> 2 votes

---
Tags: code-golf, math, number, primes, division
---


title: XKCD Calendar Facts

text:
# Question
Title: XKCD Calendar Facts
Inspiration. Posted with permission.

# Print one of the possible XKCD calendar "facts":

You can get the raw text and structure from my APL reference implementation or from Explain XKCD's transcript (including the title text just under the illustration).

### Rules

At every decision node, there must be an equal (pseudo-)random chance of each choice.

You may use all uppercase.

You must generate three sentences; a question, a reason, and a title text.

The three sentences should be ended by `?`, `.`, and `.` respectively, and separated from each other by a single space.

The only extra white-space you may include is one trailing space and/or line break.

### Examples

`Did you know that the Latest Sunset drifts out of sync with the Zodiac because of time zone legislation in Indiana? Apparently it's getting worse and no one knows why. While it may seem like trivia, it has to be corrected for by GPS satellites.`

`Did you know that Leap Year happens later every year because of precession of the equator? Apparently scientists are really worried. While it may seem like trivia, it is taken advantage of by high-speed traders.`

`Did you know that Easter drifts out of sync with the atomic clock in Colorado because of a decree by the pope in the 1500s? Apparently scientists are really worried. While it may seem like trivia, it causes huge headaches for software developers.`

# Answer
> 7 votes
# Befunge-93, ~~1959~~ 1930 bytes

```
"#~$}%|&{'zwy#x$-#w$v%u&tTs*-#r$q%p&oTn0m1l2kpj#-#i$h%gFf(e)-#d#c$bC-'a(`)_*E+"v
v"#*_?F@%A$B#C3DYE,F+G*-TH&I%J$K#L$M#-'NCO$P#Q#RjSFT%U$V#-<W;-cX(Y'Z&[%\$]#^cF"<
>">$=%<#;$:%9F$*8+-#7$6C5/4#3$-C23-#1$0C*#/$.C$:-#,$+C*#)$(C$A'#&$%C$J#"75*-0\:v
$::"P"vv-*84:-*57$$_1-\1+::"P"%\v>+>\1-:v>-#1:#$>#\_:$#<$:#v_".",@v/"P"\%"P"::\_
>\#%4#<3g/7+g"!"-:!^!:\,g+7/"P"<<^1?<*2\_$\%1++64*g48*-^<<<>75*-0v>7+g84*-+\1-:^
#<<<*2\>#$$:0\`#$_\$55++:64*g48*-90^https://xkcd.com/1930/^<<<<<<>#\\:#< >#<>#<^

3Did you know that %the %fall'spring) equinox'winter'summer" )solstice)Olympics!
)earliest'latest(sunrise'sunset0daylight saving"s& time&leap $day%year'Easter(ha
rvest&super&blood& moon3Toyota Truck Month+Shark Week)happens (earlier&later2at
the wrong time, every year=drifts out of sync with the $sun%moon'zodiac*Gregoria
n&Mayan&lunar'iPhone* calendar9atomic clock in Colorado'might +not happen-happen
 twice+ this year- because of :time zone legislation in (Indiana(Arizona'RussiaB
a decree by the Pope in the 1500s+precession*libration)nutation)libation-eccentr
icity*obliquity) of the -earth's axis(equator/Prime Meridian3International Date,
Mason-Dixon& Line8magnetic field reversal:an arbitrary decision by 2Benjamin Fra
nklin-Isaac Newton$FDR.? Apparently Rit causes a predictable increase in car acc
idents@that's why we have leap seconds>scientists are really worriedEit was even
 more extreme during the +Bronze Age(Ice Age+Cretacious&1990sFthere's a proposal
 to fix it, but it 2will never happen;actually make things worse7is stalled in C
ongress:might be unconstitutionalHit's getting worse and no one knows whyE. Whil
e it may seem like trivia, it Ncauses huge headaches for software developersLis
taken advantage of by high-speed tradersFtriggered the 2003 Northeast BlackoutJh
as to be corrected for by GPS satellitesRis now recognized as a major cause of W
orld War I" "# "$) (6DLTV`b$ "$&% "$&2# *B& "$&(*% *,PR& "$&2>% "$&(

```

Try it online!

**Explanation**

In the first three lines, we start by building up a kind of state table on the stack, representing the graph of all possible sentences. These stack entries are grouped into pairs, so there is first a string item, and then a jump or branch. Where necessary, the graph is padded with empty strings and zero-length jumps in order to meet this requirement.

Our main loop then begins by popping a number, representing a string item, off the stack. This number is interpreted as an offset into the string table in the lower section of the source. The string table is essentially a kind of linked list, wrapped over multiple lines to fit into Befunge's constrained memory space.

After outputting a string, the next item on the stack is either a jump or branch. If the number is less than 32, it's a jump, which we interpret by dropping that many pairs of items from the stack. If the number is 32 or more, it's a branch, and we use the value (minus 32) to lookup the branch details from the table on the last line of the source.

The entries in the branch table each consist of a count, followed by a list of offsets. Once we know which branch to use, we simply generate a random number, modulo the branch count, to lookup the appropriate offset. This offset is then interpreted as a jump, dropping the required number of items from the stack.

We repeat this process, outputting a string, then performing a jump or branch, until we run out of stack entries. At that point, we simply output a "." to mark the end of the final sentence, and then exit.

# Answer
> 5 votes
# Javascript (ES6), ~~1698~~ ~~1510~~ ~~1506~~ 1501 bytes

*Thanks to 12Me21 for fixing a bug in the code, which added 2 bytes*

`f=` and `document.write(f())` are not part of the byte count

```
f=_=>eval(`"Did you know that {the {Fall;Spring} Equinox;the {Wint;Summ}er {Solstice;Olympics};the {Earli;Lat}est Sun{rise;set};Daylight Saving{;s} Time;Leap {Day;Year};Easter;the {Harvest;Super;Blood} Moon;Toyota Truck Month;Shark Week} {happens {earlier;later;at the wrong time} every year;drifts out of sync with the {Sun;Moon;Zodiac;{Gregorian;Mayan;Lunar;iPhone} Calendar;atomic clock in Colorado};might {not happen;happen twice} this year} because of {time zone legislation in {Indian;Arizon;Russi}a;a decree by the pope in the 1500s;{{precession;eccentricity;obliquity};{lib;liber;nut}ation} of the {Moon;Sun;Earth's axis;equator;prime meridian;{international date;mason-dixon} line};magnetic field reversal;an arbitrary decision by {Benjamin Franklin;Isaac Newton;FDR}}? Apparently {it causes a predictable increase in car accidents;that's why we have leap seconds;scientists are really worried;it was even more extreme during the {{Bronz;Ic}e Age;{Cretaceou;1990}s};there's a proposal to fix it, but it {will never happen;actually makes things worse;is stalled in congress;might be unconstitutional};it's getting worse and no one knows why}. While it may seem like trivia, it {causes huge headaches for software developers;is taken advantage of by high-speed traders;triggered the 2003 Northeast Blackout;has to be corrected for by GPS satellites;is now recognized as a major cause of World War I}."`.split`{`.join`"+(a=>a[Math.random()*a.length|0])(["`.split`}`.join`"])+"`.split`;`.join`","`)
document.write(f())
```

# Answer
> 4 votes
# Python 2, 1297 bytes

*-419 bytes thanks to ovs.*

```
exec'eJxNVcGO3DYMvecriLk4m2yCSYseUqAomgYpcgkW7WHPtMSxmZElR5Jnxvv1fZQns3sybZHi4+MjfchposzR46HTnHJ988r9EXjqPb/h392Y1Mlrvns1Z421+6ye1rTQMaYz1ZErdW/d666OshkHDqG774p5D93d247kx6IxXfDx5nTGTZLNbZkmGObWDkoKpSIfjlJYp1ld6e5eBArnoFIqzgNXM55Dl5i1SLs0FqkW53kNOoyVCp8MjvmZQ4uqOpl3EJ63G+CN9xU5LFa4bBhvyUfOpy13WeZ21IeUfLtsSimab1pTZap5cUd8i3U0bwQe6SxyfEY78jxLLC+rytei7AlaLe05pzhsQBuTJ8krNYCoLeuhFkpLpXSgskZHZ60j3eCCBrhdgT0lr+y6e3wfsgwpK7dTXtszLLFdqg9jilsyx0Gi5w1NmtSRCwlVaSSXQsrsk9E0NX5bwpgqbXUhZjOonq2bje5Ry4bd3npxvBQx6Jt+UCM9ITcFGbSAB03RcrVTjUAf2aBkhZdZeSlF2SAweXFZhPq1Vf+QZrFQsz/8tt+XVvacxQlCGh1B+5YBZlzqT/PFV3FOYs3qtJooUh8UMoZt4AH6xvKV30b2DtWh44X4omWHS34soM4YxDSgPkhdfSO+1YRWx5aPA3k0vvWjpPjO6wWXWqag1g37PkTBYNBBJXjKpoTCNmgciXOvNTOkAR7UKjQmGrpPEr/zBC6+YMKPuA0RXwuzo29yrg35l8//dnfI9Sf9Nc+cUXW4Bmul1iTUQ2DPq6vcB6MWbHNpHDvOxM6pRxx43tlGAAHncYXgoYaTNRQDVsSl6I2U4hS+WqBdZEMpWBhwTjmreJNgpTMX03rEBMFDLjUL2POLrZRn5nsMx5MQD0YcVHa1gK2y07QATvfh48e9bRDgkizdVkmaE7ijmsDmhbTeU48hQt7dtptCoGgEP4uZXV0azImPYkqOQzHIbd1A1qXiVLwR8jcmNkNn3c/R6IWWiOKx1+qyddsAqdE0SK1WU7uKsIMpJrIhsO3aWNyhM+/pcVTjvSL/CiplgjAMSNaT8r0dNEau3RqXAdQLe3YjXg8pU0mHeja6PQoLmI9cNuQVBUFB/sSxgj+TNrQzAvm7MgtKgrD85o1swwAWfWvBL/v9r/QNf4vRFiV9CuyO2EVt8otxi7odmiquIsIw4N5/Hv7DKq4SgmJ5bwjsPwKvNER9gidbjyb+joDbhnhMGaJ/hNS+2lS87/4H4KM8AA=='.decode('base64').decode('zip')

```

Try it online!

The actual code:

```
from random import*
c=lambda*a:choice(a)
print'Did you know that '+c('the '+c('fall','spring')+' equinox','the '+c('winter','summer')+' '+c('solstice','olympics'),'the '+c('earliest','latest')+' '+c('sunrise','sunset'),'daylight saving'+c('','s')+' time','leap '+c('day','year'),'easter','the '+c('harvest','super','blood')+' moon','toyota truck month','shark week')+' '+c('happens '+c('earlier','later','at the wrong time')+' every year','drifts out of sync with the '+c('sun','moon','zodiac',c('gregorian','mayan','lunar','iPhone')+' calendar','atomic clock in colorado'),'might '+c('not happen','happen twice')+' this year')+' because of '+c('time zone legislation in '+c('indiana','arizona','russia'),'a decree by the Pope in the 1500s',c('precession','libation','nutation','libation','eccentricity','obliquity')+' of the '+c('moon','sun',"earth's axis",'equator','prime meridian',c('international date','mason-dixon')+' line'),'magnetic field reversal','an arbitrary decision by '+c('Benjamin Franklin','Isaac Newton','FDR'))+'? Apparently '+c('it causes a predictable increase in car accidents',"that's why we have leap seconds",'scientists are really worried','it was even more extreme during the '+c('bronze age','ice age','cretacious','1990s'),"there's a proposal to fix it, but it "+c('will never happen','actually make things worse','is stalled in Congress','might be unconstitutional'),"it's getting worse and no one knows why")+'. While it may seem like trivia, it '+c('causes huge headaches for software developers','is taken advantage of by high-speed traders','triggered the 2003 Northeast Blackout','has to be corrected for by GPS satellites','is now recognized as a major cause of World War I')+'.'

```

That was tiring. I haven't even done basic golfing. Somebody please write a script to golf this.

# Answer
> 3 votes
# Charcoal, 806 bytes

```
≔”}‽÷⌊＆β¶&⁰5EＹB∕¤ⅉ‖≧Ｉ2[y·↔m⁷b∕¶⎆w‹ta≔Þ…¤eN⌕⟦1H}⁷φb$≧xζ→j5⮌↗2Σ↶C$JiψT↧⊘ν；{Ｆκⅉ⊘Ｖ⁵)}LＺ)←‴Ｆ9cＣＩj+ＦＪ➙Ｎ¶℅Ｐφ⦄≧πΦjt/;⊗…→⎇↓y⁻OD¤ＨRw2◧eE≦⊗▶⁴Ｕμ4⁶⊟Ｐ}⁼Ruf→u≧″℅9ξ→Ｗ⊗7≧↨↥ω⎚,_-,*U∕$⊖τＪb4%Ｌ'⪪*⎇⊕>Þ↨ＩQ.＆ＸVSv⧴×↑Ｎ:εγC~f≔hI¶⊖⎇Ｎ6ydy"⁸？⁷∕Ｏυ⁻～Þ⁶πv″ZOgΦ✂⊘qＶ↓Ｙ5U,fν¶⁼⟲Ｙ⁺⪪“↓‹5Hψ.>⊕LＳ⁸◨›±3¤�[<⊟D´ＹυΣOR↓↓g⟧⎈″:;9≧¿×➙ρlZσ31‴8↖HＸυ3@⁺�@δIΣ≔⁺@ⅉＣＸ⎇",Ｈ²⁻↥uνu⎚⌊ÀＷ⊘∕Ｕ ψu]q➙⟲BoF⧴Ｑψ8)Ｚk⌕⊗ü；≡N±$⊞QＵ≕⁹↘NYFY?⊗↖\≦∧₂!Ｆd⌈B"η№⁻⎈Ｏ2jηＱμfÞωσdJ↧Àκ«ⅈ∕+¤êＥ�№Ｆ´⟲τ₂Ｇξr1⦃:>Oa²Ｏ[)¬X⎚∧Ｖ⊖«⪫Ｊ⁼0✂⦄Ｂlν≦&C₂？⁹κIＷÞ⁶≕>u/EKπd4ζ¤h]≕Ｄ@;ＶＷＲ$▷ω≔ＢU″″◧⁸|%↔φ；Φ?@R:↙!,⧴¹3Ｈ%⁸⧴↨⁵＆⁼E¶Ｎ Ｖ⬤⌊←}⁸⁺aw⌈Vς2A§A⟦Ｗ3«；{aZKl⊞Lξd⌊2≦2？⎈ＯＭ↔ü？⎚_Q▶δMp>{✂Mx§+↔⎆}Ｃκ·W∧Ｓd⎇⁹_ςCüI.Ｇ↓x≕χ«]n⦄&➙{‽ι⦃⁺^⦃Ｊk⎈O+oκs◧¿#W↙ＱＲ[Ｌα±´@⁰¶◧⊗βυ⊕⁴…«✳τi"TＷι＆=l¦⦄Þ⪪Þ▷‴υγ±A↥2⭆⁴≕↖≔…Ｌ¦ê⊘↥Ｂwψ¦⊘⊕*YkxAyg-'≦sΦd4◨υÀ？⁶[)…ＷS×∧ηt\e↗⊕Ｘκ≕№q₂‽Az←ＥＲT◨⟦◨<1↧Φ…⊗Ｅ›c*«Ｒ↥M6-±⌀↑F⟲#π'F5/±κ；↗～＆ζＴUI⁺U⦃⸿?^↙i⧴t”θＦβ≔⁺⁺§⪪θι⁰‽✂⪪θι¹±¹¦¹⊟⪪θιθθ

```

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

```
 ”....”                             Compressed string
≔      θ                            Assign to `q`
         β                          Lowercase letters
        Ｆ                           Loop over each letter
              ⪪θι   ⪪θι      ⪪θι    Split `q` at that letter
             §   ⁰                  First string in split (i.e. prefix)
                   ✂   ¹±¹¦¹        Slice split excluding prefix and suffix
                  ‽                 Select random element
                            ⊟       Pop last string (i.e. suffix)
           ⁺⁺                       Concatenate
          ≔                     θ   Assign to `q`
                                 θ  Print `q`

```

# Answer
> 3 votes
# , ~~1903~~ ~~1751~~ 1743 bytes

A simple brute-force solution. Might be some way to golf it down some more.

```
p=paste
P=paste0
s=function(...)sample(c(...),1)
C='calendar'
T='the'
P(p('Did you know that',s(p(T,s('Fall','Spring'),'Equinox'),p(T,s('Winter','Summer'),s('Solstice','Olympics')),p(T,s('Earliest','Latest'),s('Sunrise','Sunset')),P('Daylight Saving',s('s',''),' Time'),p('Leap',s('Day','Year')),'Easter',p(T,s('Harvest','Super','Blood'),'Moon'),'Toyota Truck Month','Shark Week'),s(p('happens',s('earlier','later','at the wrong time'),'every year'),p('drifts out of sync with the',s('Sun','Moon','Zodiac',p('Gregorian',C),p('Mayan',C),p('Lunar',C),p('iPhone'),'atomic clock in Colorado')),p('might',s('not happen','happen twice'),'this year')),'because of',s(p('time zone legislation in',s('Indiana','Arizona','Russia')),'a decree by the pope in the 1500s',p(s('precession','libration','nutation','libation','eccentricity','obliquity'),'of the',s('Moon','Sun',"Earth's axis",'equator','prime meridian','international date line','mason-dixon line')),'magnetic field reversal',p('an arbitrary decision by',s('Benjamin Franklin','Isaac Newton','FDR')))),'? Apparently ',s('it causes a predictable increase in car accidents',"that's why we have leap seconds",'scientists are really worried',p('it was even more extreme during the',s('Bronze Age','Ice Age','Cretaceous','1990s')),p("there's a proposal to fix it, but it",s('will never happen','actually makes things worse','is stalled in congress','might be unconstitutional')),"it's getting worse and no one knows why"),'. While it may seem like trivia, it ',s('causes huge headaches for software developers','is taken advantage of by high-speed traders','triggered the 2003 Northeast Blackout','has to be corrected for by GPS satellites','is now recognized as a major cause of World War I'),'.')

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~1949~~ 1938 bytes

```
import System.Random
data T a=N a[T a](T a)|P Char(T a)|E
l s=N s[]E
t=N"the"
w=map l.words
k=map l.lines
d=N""
g!a|(i,h)<-randomR(0,length a-1)g=(a!!i,h)
g#E=("",g)
g#(P c n)|(e,v)<-g#n=(c:e,v)
g#(N s[]n)|(e,v)<-g#n=([' '|s>""]++s++e,v)
g#(N s c n)|(p,q)<-g!c,(m,h)<-q#p,(e,v)<-h#n=([' '|s>""]++s++m++e,v)
tail.fst.(#N"Did you know that"[t(w"fall spring")$l"equinox",t(w"winter summer")$d(w"solstice olympics")E,t(w"earliest latest")$d(w"sunrise sunset")E,N"daylight"(w"saving savings")$l"time",N"leap"(w"day year")E,l"easter",t(w"harvest super blood")$l"moon",l"Toyota truck month",l"shark week"](d[N"happens"(k"earlier\nlater\nat the wrong time")$l"every year",N"drifts out of sync with the"[l"sun",l"moon",l"zodiac",d(w"gregorian mayan lunar iPhone")$l"calendar",l"atomic clock in Colorado"]E,N"might"(k"not happen\nhappen twice")$l"this year"]$N"because of"[N"time zone legislation in"(w"Indiana Arizona Russia")E,l"a decree by the Pope in the 1500s",d(w"precession libration nutation libation eccentricity obliquity")$N"of the"(k"moon\nsun\nEarth's axis\nequator\nprime meridian\ninternational date line\nMason-Dixon line")E,l"magnetic field reversal",N"an arbitrary decision by"(k"Benjamin Franklin\nIsaac Newton\nFDR")E]$P '?'$N"Apparently"[l"it causes a predictable increase in car accidents",l"that's why we have leap seconds",l"scientists are really worried",N"it was even more extreme during the"[l"bronze age",l"ice age",l"cretaceous",l"1990's"]E,N"there's a proposal to fix it, but it"(k"will never happen\nactually makes things worse\nis stalled in congress\nmight be unconstitutional")E,l"it's getting worse and no one knows why"]$P '.'$N"While it may seem like trivia, it"(k"causes huge headaches for software developers\nis taken advantage of by high-speed traders\ntriggered the 2003 Northeast Blackout\nhas to be corrected for by GPS satellites\nis now recognized as a major cause of World War I")$P '.'E))<$>newStdGen

```

Try it online! (Has an extra 2 bytes for `f=`)

Mostly wrote this just so I could create the data structure. This could definitely be improved but I'm tired and I have to leave soon anyway. I think capitalization is mostly right but I'll convert it all to caps if it's wrong. That won't change the byte count or anything since I haven't done anything weird with the string data.

Basic idea is a linked list of trees where each node is either empty (`E`), a punctuation mark (`P`) or a string label with children. All nodes except `E` nodes have a "follower" node that comes after them.

EDIT: just noticed a spelling mistake (I wrote "no one know why" instead of "no one knows why") so I had to add a byte to fix it but I also found some code that could be cut out

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

```
f=(s=btoa`...`)=>/h/.test(s)?f(s.replace(/g([^gi]+)i/,(_,x)=>` ${(x=x.split`h`)[Math.random()*x.length|0]} `)):s.replace(/[a-f]/g,x=>" '-?,."['0x'+x-10]).replace(/ +(\W)/g,'$1')

```

where the `...` represents the result of running `atob()` on this string and replacing `\` with `\\`, ``` with `\``, 0x00 with `\0`, and 0x0D with `\r`:

```
DIDaYOUaKNOWaTHATgTHEgFALLhSPRINGiEQUINOXhTHEgWINTERhSUMMERigSOLSTICEhOLYMPICSihTHEgEARLIESThLATESTigSUNRISEhSUNSETihTHEgHARVESThSUPERhBLOODiMOONhDAYLIGHTgSAVINGhSAVINGSiTIMEhLEAPgDAYhYEARihEASTERhTOYOTAaTRUCKaMONTHhSHARKaWEEKigHAPPENSgEARLIERhLATERhATaTHEaWRONGaTIMEiEVERYaYEARhDRIFTSaOUTaOFaSYNCaWITHaTHEgSUNhMOONhZODIAChgGREGORIANhMAYANhLUNARhIPHONEiCALENDARhATOMICaCLOCKaINaCOLORADOihMIGHTgNOTaHAPPENhHAPPENaTWICEiTHISaYEARiBECAUSEaOFgTIMEaZONEaLEGISLATIONaINgINDIANAhARIZONAhRUSSIAihAaDECREEaBYaTHEaPOPEaINaTHEa1500ShgPRECESSIONhLIBRATIONhNUTATIONhLIBRATIONhECCENTRICITYhOBLIQUITYiOFaTHEgSUNhMOONhEARTHbSaAXIShEQUATORhPRIMEaMERIDIANhINTERNATIONALaDATEaLINEhMASONcDIXONaLINEihMAGNETICaFIELDaREVERSALhANaARBITRARYaDECISIONaBYgBENJAMINaFRANKLINhISSACaNEWTONhFDRiidaAPPARENTLYgITaCAUSESaAaPREDICTABLEaINCREASEaINaCARaACCIDENTShTHATbSaWHYaWEaHAVEaLEAPaSECONDShSCIENTISTSaAREaREALLYaWORRIEDhITaWASaEVENaMOREaEXTREMEaDURINGaTHEgBRONZEaAGEhICEaAGEhCRETACEOUSh1990SihTHEREbSaAaPROPOSALaTOaFIXaITeaBUTaITgWILLaNEVERaHAPPENhACTUALLYaMAKESaTHINGSaWORSEhISaSTALLEDaINaCONGRESShMIGHTaBEaUNCONSTITUTIONALihITbSaGETTINGaWORSEaANDaNOaONEaKNOWSaWHYifaWHILEaITaMAYaSEEMaLIKEaTRIVIAeaITgCAUSESaHUGEaHEADACHESaFORaSOFTWAREaDEVELOPERShISaTAKENaADVANTAGEaOFaBYaHIGHcSPEEDaTRADERShTRIGGEREDaTHEa2003aNORTHEASTaBLACKOUThHASaTOaBEaCORRECTEDaFORaBYaGPSaSATELLITEShISaNOWaRECOGNIZEDaASaAaMAJORaCAUSEaOFaWORLDaWARaIif

```

Try it here, minus the `btoa`:

```
f=(s="DIDaYOUaKNOWaTHATgTHEgFALLhSPRINGiEQUINOXhTHEgWINTERhSUMMERigSOLSTICEhOLYMPICSihTHEgEARLIESThLATESTigSUNRISEhSUNSETihTHEgHARVESThSUPERhBLOODiMOONhDAYLIGHTgSAVINGhSAVINGSiTIMEhLEAPgDAYhYEARihEASTERhTOYOTAaTRUCKaMONTHhSHARKaWEEKigHAPPENSgEARLIERhLATERhATaTHEaWRONGaTIMEiEVERYaYEARhDRIFTSaOUTaOFaSYNCaWITHaTHEgSUNhMOONhZODIAChgGREGORIANhMAYANhLUNARhIPHONEiCALENDARhATOMICaCLOCKaINaCOLORADOihMIGHTgNOTaHAPPENhHAPPENaTWICEiTHISaYEARiBECAUSEaOFgTIMEaZONEaLEGISLATIONaINgINDIANAhARIZONAhRUSSIAihAaDECREEaBYaTHEaPOPEaINaTHEa1500ShgPRECESSIONhLIBRATIONhNUTATIONhLIBRATIONhECCENTRICITYhOBLIQUITYiOFaTHEgSUNhMOONhEARTHbSaAXIShEQUATORhPRIMEaMERIDIANhINTERNATIONALaDATEaLINEhMASONcDIXONaLINEihMAGNETICaFIELDaREVERSALhANaARBITRARYaDECISIONaBYgBENJAMINaFRANKLINhISSACaNEWTONhFDRiidaAPPARENTLYgITaCAUSESaAaPREDICTABLEaINCREASEaINaCARaACCIDENTShTHATbSaWHYaWEaHAVEaLEAPaSECONDShSCIENTISTSaAREaREALLYaWORRIEDhITaWASaEVENaMOREaEXTREMEaDURINGaTHEgBRONZEaAGEhICEaAGEhCRETACEOUSh1990SihTHEREbSaAaPROPOSALaTOaFIXaITeaBUTaITgWILLaNEVERaHAPPENhACTUALLYaMAKESaTHINGSaWORSEhISaSTALLEDaINaCONGRESShMIGHTaBEaUNCONSTITUTIONALihITbSaGETTINGaWORSEaANDaNOaONEaKNOWSaWHYifaWHILEaITaMAYaSEEMaLIKEaTRIVIAeaITgCAUSESaHUGEaHEADACHESaFORaSOFTWAREaDEVELOPERShISaTAKENaADVANTAGEaOFaBYaHIGHcSPEEDaTRADERShTRIGGEREDaTHEa2003aNORTHEASTaBLACKOUThHASaTOaBEaCORRECTEDaFORaBYaGPSaSATELLITEShISaNOWaRECOGNIZEDaASaAaMAJORaCAUSEaOFaWORLDaWARaIif")=>/h/.test(s)?f(s.replace(/g([^gi]+)i/,(_,x)=>` ${(x=x.split`h`)[Math.random()*x.length|0]} `)):s.replace(/[a-f]/g,x=>" '-?,."['0x'+x-10]).replace(/ +(\W)/g,'$1')
document.write(f())
```

# Answer
> 2 votes
# APL (Dyalog), 1302 bytes

```
'[a-z]'⎕R' \u&'⊢'⍠[^⍠⌸]*⌸'⎕R{(?∘≢⊃⊢)⍵.Match(∊⊆⊣)⎕AV}⍣≡'DIDyOUkNOWtHAT⍠tHE⍠fALL⌺sPRING⌸eQUINOX⌺tHE⍠wINTE⌺sUMME⌸R⍠sOLSTICE⌺oLYMPICS⌸⌺tHE⍠eARLI⌺lAT⌸ESTsUN⍠RISE⌺SET⌸⌺dAYLIGHTsAVING⍠ ⌺S ⌸TIME⌺lEAP⍠dAY⌺yEAR⌸⌺eASTER⌺tHE⍠hARVEST⌺sUPER⌺bLOOD⌸mOON⌺tOYOTAtRUCKmONTH⌺sHARKwEEK⌸⍠hAPPENS⍠eARLIER⌺lATER⌺aTtHEwRONGtIME⌸eVERYyEAR⌺dRIFTSoUToFsYNCwITHtHE⍠sUN⌺mOON⌺zODIAC⌺⍠gREGORIAN⌺mAYAN⌺lUNAR⌺iPHONE⌸cALENDAR⌺aTOMICcLOCKiNcOLORADO⌸⌺mIGHT⍠nOThAPPEN⌺hAPPENtWICE⌸tHISyEAR⌸bECAUSEoF⍠tIMEzONElEGISLATIONiN⍠iNDIAN⌺aRIZON⌺rUSSI⌸A⌺adECREEbYtHEpOPEiNtHE 1500S⌺⍠pRECESSION⌺lIBRATION⌺nUTATION⌺lIBATION⌺eCCENTRICITY⌺oBLIQUITY⌸oFtHE⍠mOON⌺sUN⌺eARTH''SaXIS⌺eQUATOR⌺pRIMEmERIDIAN⌺⍠iNTERNATIONALdATE⌺mASON-DIXON⌸lINE⌸⌺mAGNETICfIELDrEVERSAL⌺aNaRBITRARYdECISIONbY⍠bENJAMINfRANKLIN⌺iSAACnEWTON⌺fDR⌸⌸?aPPARENTLY⍠iTcAUSESapREDICTABLEiNCREASEiNcARaCCIDENTS⌺tHAT''SwHYwEhAVElEAPsECONDS⌺sCIENTISTSaRErEALLYwORRIED⌺iTwASmOREeXTREMEdURINGtHE ⍠BRONZEaGE⌺ICEaGE⌺CRETACEOUS⌺1990S⌸⌺tHERE''SapROPOSALtOfIXiT,bUTiT⍠wILLnEVERhAPPEN⌺aCTUALLYmAKEStHINGSwORSE⌺iSsTALLEDiNcONGRESS⌺mIGHTbEuNCONSTITUTIONAL⌸⌺iT''SgETTINGwORSEaNDnOoNEkNOWSwHY⌸.wHILEiTmAYsEEMlIKEtRIVIA,iT⍠cAUSEShUGEhEADACHESfORsOFTWAREdEVELOPERS⌺iStAKENaDVANTAGEoFbYhIGH-SPEEDtRADERS⌺tRIGGEREDtHE 2003nORTHEASTbLACKOUT⌺hAStObEcORRECTEDfORbYgPSsATELLITES⌺iSnOWrECOGNIZEDaSamAJORcAUSEoFwORLDwARi⌸.'

```

Try it online!

Adám helped with this one...then challenged me to finish it. :P

-11 thanks to Adám (using his new SBCS tool I can abuse the encoding without extra cost).

# Answer
> 0 votes
# APL (Dyalog Unicode), 1593 bytes

`C←?∘≢⊃⊢`
`S←C'|'∘≠⊆⊢`
`∊'Did you know that '(C('the '(S'Fall|Spring')' Equinox ')('the '(S'Winter |Summer ')(S'Solstice |Olympics '))('the '(S'Earliest |Latest ')(S'Sunrise |Sunset '))('Leap ',S'Day |Year ')'Easter '('the '(S'Harvest|Super|Blood')' Moon ')'Toyota Truck Month '('Daylight Savings Time '~C's∘')'Shark Week ')(C('happens '(S'earlier|later|at the wrong time')' every year ')('drifts out of sync with the '(S'Sun |Moon |Zodiac |atomic clock in Colorado|',' Calendar ',⍨S'Gregorian|Mayan|Lunar|iPhone'))('might '(S'not happen|happen twice')' this year '))'because of '(C('time zone legislation in ',S'Indiana|Arizona|Russia')'a decree by the pope in the 1500s'((S'precession|libration|nutation|libation|eccentricity|obliquity')' of the '(S'Moon|Sun|Earth''s axis|equator|prime meridian|',' line',⍨S'international date|mason-dixon'))'magnetic field reversal'('an arbitrary decision by ',S'Benjamin Franklin|Isaac Newton|FDR'))'? Apparently '(C'it causes a predictable increase in car accidents'('it was even more extreme during the ',S'Bronze Age|Ice Age|Cretaceous|1990s')'that''s why we have leap seconds'('there''s a proposal to fix it, but it ',S'will never happen|actually makes things worse|is stalled in congress|might be unconstitutional')'scientists are really worried' 'it''s getting worse and no one knows why')'. While it may seem like trivia, it '(S'causes huge headaches for software developers|is taken advantage of by high-speed traders|triggered the 2003 Northeast Blackout|has to be corrected for by GPS satellites|is now recognized as a major cause of World War I')'.'`

Try it online!

Defines two helper functions and then uses them in one giant expression:

`C←` C (for **C**hoose) is
`?∘≢` a random number up to the number of elements in the argument
picks
from the arguments

`S←` S (for **S**plit and **S**elect) is
`C` choose among
`'|'∘≠` the where-not-pipe
partitioned
argument

**ϵ**nlist (flatten)
`C` chooses from a list of strings and `S` chooses from the substrings of a `|` delimited string, and these are just used in combination to construct a "fact".

---
Tags: code-golf, string, random, combinatorics
---


title: If A-B be in A-B A else B eh?

text:
# Question
Title: If A-B be in A-B A else B eh?
Given two integers, A and B, output A if A-B (A minus B) is in A-B (A to B), otherwise output B.

"A minus B" is standard subtraction.

"A to B" is the range of integers starting at A and ending at B, including both A and B. For example:

```
1 to 4: 1, 2, 3, 4
-2 to 5: -2, -1, 0, 1, 2, 3, 4, 5
3 to -1: 3, 2, 1, 0, -1
7 to 7: 7

```

**The shortest code in bytes wins.**

## Test Cases

```
A B Output
1 4 4
-2 5 5
3 -1 -1
7 7 7
90 30 90
90 -30 -30
-90 30 30
-90 -30 -90
-2 -2 -2
-2 -1 -2
-2 0 -2
-2 1 1
-2 2 2
-1 -2 -2
-1 -1 -1
-1 0 -1
-1 1 1
-1 2 2
0 -2 -2
0 -1 -1
0 0 0
0 1 1
0 2 2
1 -2 -2
1 -1 -1
1 0 1
1 1 1
1 2 2
2 -2 -2
2 -1 -1
2 0 2
2 1 2
2 2 2

```

Original Chat-Mini-Challenge

# Answer
> 45 votes
# Python, 27 bytes

```
lambda a,b:[a,b][2*b*b>a*b]

```

Try it online!

An arithmetic formula. Why is the negation of `2*b*b>a*b` equivalent to the problem condition `a-b in symrange(a,b)`?

Note that `x in symrange(a,b)` is equivalent to `0 in symrange(a-x,b-x)`. Applying this to `x=a-b` gives `0 in symrange(b,2*b-a)`. The value `0` is included in the interval unless it stretches between two positive values or two negative values. This can be stated arithmetically as "their product `b*(2*b-a)` is not positive.

Finally, take `b*(2*b-a)<=0`, and rewrite to `2*b*b<=a*b`. A byte is saved by flipping `<=` to `>` and switching the cases.

# Answer
> 11 votes
# Jelly, 5 bytes

```
_erị,

```

Try it online!

### How it works

```
_erị,  Main link. Arguments: a, b

_      Subtraction; Yield a-b.
  r    Range; yield [a, ..., b].
 e     Exists; yield 1 if a-b belongs to [a, ..., b], 0 if not.
    ,  Pair; yield [a, b].
   ị   At-index; yield the element of [a, b] at index 1 (a) or index 0 (b).

```

# Answer
> 8 votes
# 05AB1E, 7 bytes

Code:

```
DŸ¹Æå_è

```

Uses the **CP-1252** encoding. Try it online!

Explanation:

```
D         # Duplicate the input.
 Ÿ        # Inclusive range.
  ¹Æ      # Push the input [a, b] and compute a - b.
    å     # Check if the number exists in the range.
     _    # Boolean negate
      è   # Index at the first input

```

# Answer
> 6 votes
# PHP, 58 Bytes

```
<?=in_array(($a=$argv[1])-$b=$argv[2],range($a,$b))?$a:$b;

```

# Answer
> 6 votes
# JavaScript (ES6), 24 bytes

```
a=>b=>[a,b][2*b*b>a*b|0]

```

## Test cases

```
let f = a=>b=>[a,b][2*b*b>a*b|0]
let tests = [[1,4,4],[-2,5,5],[3,-1,-1],[7,7,7],[90,30,90],[90,-30,-30],[-90,30,30],[-90,-30,-90],[-2,-2,-2],[-2,-1,-2],[-2,0,-2],[-2,1,1],[-2,2,2],[-1,-2,-2],[-1,-1,-1],[-1,0,-1],[-1,1,1],[-1,2,2],[0,-2,-2],[0,-1,-1],[0,0,0],[0,1,1],[0,2,2],[1,-2,-2],[1,-1,-1],[1,0,1],[1,1,1],[1,2,2],[2,-2,-2],[2,-1,-1],[2,0,2],[2,1,2],[2,2,2]]
tests.map(test => `f(${test[0]})(${test[1]}) == ${test[2]}`).forEach(test => console.log(test, eval(test)))
```

# Answer
> 4 votes
# Python2, ~~55~~ ~~52~~ 51 bytes

```
lambda A,B:[B,A][A-B in range(min(A,B),max(A,B)+1)]

```

Try it online!

Handles every test case OP has mentioned (at the time of posting this), as the TIO suggests.

# Answer
> 4 votes
# Python 2, 37 bytes

```
lambda*s:s[min(s)<=s[1]-s[0]<=max(s)]

```

Invoke as `f(B, A)`.

# Answer
> 4 votes
# JavaScript ES6, 40 37 bytes

```
a=>b=>a-b<(a<b?a:b)|a-b>(a<b?b:a)?b:a

```

Explained:

```
a=>b=>                                   take a and b as inputs
      a-b<(a<b?a:b)                      if a-b is less than the lowest of a and b
                   |a-b>(a<b?b:a)        or a-b is greater than the largest of a and b
                                 ?b      return b
                                   :a    else return a

```

Saved 3 bytes thanks to Arnauld.

```
f=a=>b=>a-b<(a<b?a:b)|a-b>(a<b?b:a)?b:a

function t(){
    var tests = [[1,4,4],[-2,5,5],[3,-1,-1],[7,7,7],[90,30,90],[90,-30,-30],[-90,30,30],[-90,-30,-90],[-2,-2,-2],[-2,-1,-2],[-2,0,-2],[-2,1,1],[-2,2,2],[-1,-2,-2],[-1,-1,-1],[-1,0,-1],[-1,1,1],[-1,2,2],[0,-2,-2],[0,-1,-1],[0,0,0],[0,1,1],[0,2,2],[1,-2,-2],[1,-1,-1],[1,0,1],[1,1,1],[1,2,2],[2,-2,-2],[2,-1,-1],[2,0,2],[2,1,2],[2,2,2]];
    for (var test of tests) {
        console.log(`f(${test[0]},${test[1]}) == ${test[2]}`, f(test[0])(test[1])==test[2]);
    }
}

t();
```

# Answer
> 3 votes
# Mathematica, 16 bytes

```
If[2#^2>1##,##]&

```

Pure function taking two arguments in the opposite order as the OP (for example, `If[2#^2>1##,##]&[B,A]`). A port of xnor's Python answer.

# Answer
> 2 votes
## R, ~~49~~ ~~30~~ 28 bytes

```
pryr::f("if"(2*b*b>a*b,b,a))

```

Uses @xnor's logic for determining whether a-b is in a:b.

# Answer
> 2 votes
# Clojure, ~~71~~ 41 bytes

-30 bytes by using `<=` and `min`/`max` instead of `range`s.

```
#(if(<=(min % %2)(- % %2)(max % %2))% %2)

```

Checks if `(a - b)` is in the range from `a` to `b`, dispatching a return accordingly.

```
(defn eh [a b]
  ; <= accepts any number of argments, and ensures all fall within the range
    (if (<= (min a b) (- a b) (max a b))
      a
      b))

```

# Answer
> 2 votes
# PHP (7.1), 55 bytes

uses the new array destructuring syntax:

```
[,$a,$b]=$argv;echo in_array($a-$b,range($a,$b))?$a:$b;

```

Run with `-r`, provide numbers as command line arguments.

# Answer
> 2 votes
# PowerShell, ~~37~~ ~~35~~ 32 bytes

```
($a,$b=$args)[$a-$b-notin$a..$b]

```

Try it online!

Literal translation of the problem into PowerShell using the `-notin` operator. Saved three bytes by using multiple assignment and encapsulation. This works because `-` has a higher operator precedence than `-notin`, and the `( )` portion of the code is executed first and returned as an array `@($a,$b)`. However, since it's `$a,$b` rather than `$b,$a`, we need to use `-notin` to flip/flop the output result.

# Answer
> 2 votes
# Nim, 60 bytes

```
proc f(a,b:int):int=
  if a-b in min(a,b)..max(a,b):a else:b

```

Try it online!

Pretty standard as far as answers go, no big tricks in this one.

# Answer
> 1 votes
## Batch, 107 bytes

```
@set/aa=%1,r=b=%2,x=a-b
@if %a% gtr %b% set/aa=b,b=%1
@if %a% leq %x% if %x% leq %b% set/ar=%1
@echo %r%

```

# Answer
> 1 votes
# Pyth - 9 bytes

Was hoping to use more implicit input... :(

```
@Q!}-FQ}F

```

Try it online here.

# Answer
> 1 votes
# Röda, 30 bytes

```
f a,b{[b]if[2*b*b>a*b]else[a]}

```

Try it online!

It uses the formula used in xnor's answer.

Another solution (37 bytes):

```
f a,b{[a]if[a-b in[seq(a,b)]]else[b]}

```

Try it online!

# Answer
> 1 votes
# Java 7, ~~84~~ ~~60~~ 58 bytes

```
int c(int a,int b){return(a<b?a:b)>a-b|(a<b?b:a)<a-b?b:a;}

```

# Java 8, 37 bytes

```
a->b->(a<b?a:b)>a-b|(a<b?b:a)<a-b?b:a

```

**Explanation:**

```
int c(int a, int b){          // method with two integer parameters and integer return-type
  return (a<b ? a : b) > a-b  //  if smallest of the input is larger than a-b
       | (a<b ? b : a) < a-b  //    or if the largest of the input is smaller than a-b
    ? b                       //   return b
    :                         //  else
      a                       //   return a
}                             // end of method

```

**Test code:** Try it here.

# Answer
> 1 votes
# \>\<\>, 21 bytes

Makes use of @xnor's trick. We use `-v B A` to prepopulate the stack. (`-v A B` is +1 byte).

```
:01pr:11p::2**r*)1gn;

```

Try it online!

## Explanation

```
                        Input: [B, A] on stack.
:01pr:11p::2**r*)1gn;
:                       Duplicate.           [B, A, A]
 01p                    Push A to [0,1].     [B, A]
    r                   Reverse              [A, B]
     :                  Duplicate.           [A, B, B]
      11p               Push B to [1,1].     [A, B]
         ::             Duplicate x 2.       [A, B, B, B]
           2            Push 2.              [A, B, B, B, 2]
           2**          Compute 2*B*B.       [A, B, 2*B*B]
              r         Reverse.             [2*B*B, B, A]
               *        Compute A*B.         [2*B*B, A*B]
                )       >                    [2*B*B > A*B]
                 1      Push 1.              [2*B*B > A*B, 1]
                  g     If 2*B*B > A*B
                         get B, else get A.  [2*B*B > A*B ? B : A]
                   n    Output as number.
                    ;   Terminate.

```

# Answer
> 1 votes
## Swift \- ~~38~~ ~~30~~ 22 bytes

Saved 8 bytes thanks to @Matt

```
print(a...b~=a-b ?a:b)

```

Try it at IBM Swift Sandbox online!

---

## Or 21 bytes:

(thanks to **@xnor**'s formula) and saved 8 bytes thanks to @Matt

```
print(2*b*b>a*b ?a:b)

```

---

Swift is not the best language for golfing (it's very rigid), so if you see any other golfing opportunity, I'll totally edit the answer.

# Answer
> 1 votes
# Ruby, ~~27~~ 22 bytes

```
->a,b{(b*a<2*b*b)?b:a}

```

Try it online!

Nothing innovative here. The simple math behind it:

```
(A<=A-B<=B or B<=A-B<=A)

```

can be written as

```
(B>=0 and A>=2B) or (B<=0 and A<=2B)

```

that is: if A-2B has the same sign as B, we are in the range.

# Answer
> 1 votes
# SpecBAS - 38 btes

```
1 INPUT a,b: ?IIF(a-b IN [a TO b],a,b)

```

`IIF` is an inline-IF-THEN-ELSE, to print the correct value.

# Answer
> 1 votes
# Haskell, 21 bytes

```
a!b|b*a<2*b*b=b|0<1=a

```

Try it online!

## Readable

```
func :: Int -> Int -> Int
func a b
    | b*a < 2*b*b = b
    | otherwise = a

```

## Explanation

Uses @xnor's formula to check whether a-b is in range. Nothing special besides that.

# Answer
> 1 votes
# PHP 7 - 45 Bytes

```
echo(in_array($a-$b,range($a,$b))?$a:$b)==$c;

```

# Answer
> 1 votes
## Haskell, 58 bytes

Just recently I fell in love with arrows again. Unfortunately they require us to work with tuples instead of binary functions. And of course Haskell does not have a symmetrical `range` function.

```
import Control.Arrow
u=uncurry
app<<<elem.u(-)&&&(u enumFromTo<<<u min&&&u max)

```

# Answer
> 1 votes
# Octave, 55bytes

```
@(a,b)(c=b*~[find((a:1-2*(b<a):b)==(a-b)) 0](1))+(a*~c)

```

This could probably be optimised further. I'll add an explanation later.

# Answer
> 1 votes
# Ti-Basic (TI-84 Plus CE), ~~26 24~~ 23 bytes

```
Prompt A,B
A-B≥A and A-B≤B
AAns+Bnot(Ans

```

TI-Basic is a tokenized language; all tokens used are one-byte tokens.

`Prompt` prompts you for the two numbers.

`A-B≥A and A-B≤B` checks if A-B is between A and B (inclusive); this returns a 1 if true and a zero if false, which is stored to `Ans`.

Since we are returning A if A-B is between A and B, we multiply A by Ans, which will be A if we are supposed to return A, and 0 otherwise.

Next, we add `Bnot(Ans` to it. If Ans was 1 (truthy), we `not(` it and get 0, thus our sum is A. If Ans was 0 (falsy), we `not(` it to get 1, which we multiply by B and add to 0 to get B.

The last evaluation in TI-Basic is implicitly returned.

-2 bytes thanks to Scott Milner

# Answer
> 1 votes
# Pyt, 32 bytes

```
←Đ←Đ3Ș⇹Đ3ȘĐ4Ș3Ș-3Ș⇹Ř∈Đ3Ș⇹¢*3Ș⇹*+

```

Takes A and B from stdin as two separate inputs

Explanation:

AABB -\> ABBA -\> ABAB -\> ABABB -\> ABBBA -\> ABBBAA -\> ABAABB -\> ABABBA -\> ABABC -\> ABCBA -\> ABCAB -\> ABC\[A,...,B\] -\> ABD -\> ABDD -\> ADDB -\> ADBD -\> AD{B\*(1-D)} -\> {B\*(1-D)}AD -\> {B\*(1-D)}+{A\*D}

where: C=B-A and D=C∈\[A,...,B\] (1 if true, 0 if false)

# Answer
> 0 votes
# Ohm, 10 bytes (CP437)

There's probably a golfier way to do this, but the strictly-typed nature of Ruby makes this difficult.

```
G┼┘-îε?┼¿┘

```

# Answer
> 0 votes
# Perl 6,  ~~31 29~~  24 bytes

```
{$^a-$^b==any($a...$b)??$a!!$b}

```

Try it

```
{$^a-$^b∈($a...$b)??$a!!$b}

```

Try it

```
->\a,\b{2*b*b>a*b??b!!a}
->\a,\b{2*b²>a*b??b!!a}

```

Try it

# Answer
> 0 votes
# Kotlin, 43 bytes

```
{a,b->if(a-b in a..b||a-b in b..a)a else b}

```

This is the one time that I am grateful that kotlin ranges are inclusive.

You could alternatively do it using xnor's algorithm with 28 bytes:

```
{a,b->if(2*b*b>a*b)b else a}

```

Test Suite

# Answer
> 0 votes
# MATL, 13 bytes

```
tPdGSl&)&:mo)

```

Try it at **MATL Online**

**Explanation**

```
    % Implicitly grab input as a 2-element array
t   % Duplicate the input
Pd  % Flip the order and compute the difference
GS  % Grab the input again and sort it
l&) % Break the two elements of the array into two stack elements
&:  % Create the array from the smaller to the larger element
m   % Check for membership (returns FALSE or TRUE)
o   % Convert FALSE to 0 and TRUE to 1
)   % Use this as a modular index into the initial array
    % Implicitly display the result

```

# Answer
> 0 votes
# Japt, 14 bytes

```
òV bU-V ¨0?U:V

```

Try it online!

# Answer
> 0 votes
# Ohm, 25 bytes

```
IIGÉ┼┘-E;?┼¿┘;,

```

Expanation:

```
IIGÉ┼┘-E;?┼¿┘;,
II              ■Inputs twice
  G             ■Range a..b
   É            ■any {
    ┼┘-E        ■  firstInput-secondInput==element
        ;       ■}
         ? ¿ ;  ■if {
          ┼     ■  firstinput
           ¿    ■}else{
            ┘   ■  secondinput
             ;  ■}
              , ■Print

```

# Answer
> 0 votes
# Google Sheets, 49 bytes

*-2 bytes because Google Sheets automatically closes brackets*

```
=MINUS(A1,A2
=IF(AND(GTE(A1,A3),LTE(A2,A3)),A1,A2

```

Inputs are in the cells A1 and A2. Assumes cell A3 is selected after input is recieved.

The newline isn't actually a newline, it's just pressing enter.

The code is pretty readable, so I doubt an explanation is needed.

# Answer
> 0 votes
# Octave, ~~37~~ 34 bytes

```
@(a)a(2-ismember(-diff(a),a:a(2)))

```

This is an anonymous function that takes the input values as an array of two elements: `[-90, 30]`.

**Breakdown:**

```
@(a)a(                           )  % Function that takes a variable a as input
                                    % and returns the x'th element (dependent on what's
                                    % inside the parentheses.
                 -diff(a)           % Takes the negative difference between the two

                          a:a(2)))  % A vector: -3 -2 -1 0 1 2 ...
        ismember(-diff(a),a:a(2)))  % Checks if the negative difference (a-b)
                                       % is part of the range. Returns 1 for true
    a(2-ismember(-diff(a),a:a(2)))  % Return the 2-ismember() element of the input
@(a)a(2-ismember(-diff(a),a:a(2)))  % Everything put together

```

`a(1):a(2)` is the same as `a:a(2)` since Octave automatically assumes you want the first element. That saved an additional two bytes.

I *could* save one more byte by taking the input in the different order `[b, a]`, but I figured it was cleaner this way.

# Answer
> 0 votes
# Ly, 39 bytes

```
nn&s<l>>lRy![plfR11$]p<-s>l~[<<pu;]<<u;

```

Try it online!

---
Tags: code-golf, math, number, arithmetic
---


# Question
Title: Output the language name times the number of characters
# **Challenge:**

Your task is to use any language to output that language's name times the number of character's in its name.

* Use the common name or acronym of the language.
* If there are multiple versions of a language, you need not include the version number.
* The capitalization matters.

**Examples:**

```
PHP -> PHPPHPPHP
Java -> JavaJavaJavaJava
C++ -> C++C++C++
Python 3 -> PythonPythonPythonPythonPythonPython
JavaScript -> JavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScriptJavaScript

```

# Answer
> 21 votes
# , 2 bytes

```
iV

```

Try it online!

Citing *Arnauld*, with Levenshtein distance of 1:

> I now have 15 seconds of experience in V programming. So, this may actually be golfable.

# Answer
> 16 votes
# Haskell, 16 bytes

```
h>>h
h="Haskell"

```

Try it online!

Applied on two lists, `(>>)` concatenates the second list with itself as often as the first list has elements.

---

### Point-free (19 bytes)

```
id=<<(>>)$"Haskell"

```

Try it online!

`(id=<<)` is the same as `join`, but without the need for `import Control.Monad`.

# Answer
> 16 votes
# , 7 bytes

I now have 15 seconds of experience in J programming. So, this may actually be golfable(1).

```
echo'J'

```

Try it online!

*(1) Edit: And of course it was. Thanks to @ConorO'Brien for saving 2 bytes! Using a verb:*

## 5 bytes

```
'J'"_

```

# Answer
> 15 votes
# , 11 bytes

```
3.600525004

```

Explanation:

```
3.            Required prefix for all 4 programs.
  6            Set
   00            The cell at index 0
     52          To 52 (ASCII value for '4').
       5       Print
        00      The cell at index 0.
          4   Required suffix for all 4 programs.

```

Try it online!

# Answer
> 12 votes
# Operation Flashpoint scripting language, 64 bytes

```
f={s="%1%1%1%1";format[s+"%1",format[s,"Operation Flashpoint"]]}

```

Since there is no official name for the scripting language, I'm using `Operation Flashpoint` as the name of the language.

**Call with:**

```
hint call f

```

**Output:**

# Answer
> 10 votes
# , 8 bytes

```
cat("R")

```

Try it online!

# Answer
> 8 votes
# , 12 bytes

```
f(x){x="C";}

```

Try it online! (GCC)

Saved 3 bytes with help from user202729. C has been chosen strategically, but this is pretty much GCC-specific.

# Answer
> 8 votes
# , 2 bytes

```
”M

```

Single-letter languages have a clear advantage.

Try it online!

# Answer
> 8 votes
## Retina, 12 bytes

```

Retina
.
$_

```

Try it online!

### Explanation

```

Retina

```

Initialise the string to `Retina`.

```
.
$_

```

Replace each character with the full string.

# Answer
> 8 votes
# ///, 17 bytes

```
/i/\\\//iiiiiiiii

```

Try it online!

(this prints `/////////`)

---

Naive solution is (only) 1 byte longer.

```
\/\/\/\/\/\/\/\/\/

```

Trying to remove the duplicated `i`s actually increases byte count.

```
/#/iii//i/\\\//###

```

# Answer
> 8 votes
# Verbosity, ~~458~~ 454 bytes

```
Include<Integer>
Include<MetaFunctions>
Include<Output>
Include<String>
Integer:DefineVariable<o; 1>
Output:DefineVariable<P; 0>
String:DefineVariable<s; "VerbosityVerbosityVerbosityVerbosityVerbosityVerbosityVerbosityVerbosityVerbosity">
String:DefineVariable<q; String:RemoveCharactersFromStart<s; o>>
String:DefineVariable<r; String:TakeFirstCharacters<q; o>>
Output:DisplayAsText<P; r>
DefineMain<> [
MetaFunctions:ExecuteScript<MetaFunctions@FILE>
]

```

Try it online!

Saved 4 bytes thanks to NieDzejkob!

You know your language is verbose when it's shorter to create an 81 character long string that it is to multiply a 9 character long string by 9.

# Answer
> 7 votes
# Chef, 268 bytes

```
C.

Ingredients.
102 l f
101 l e
104 l h
67 l c
4 g i

Method.
Put f into the mixing bowl.
Put e into the mixing bowl.
Put h into the mixing bowl.
Put c into the mixing bowl.
V the i.
Pour contents of the mixing bowl into the baking dish.
V the i until ved.

Serves 1.

```

Try it online!

### More idiomatic (565 bytes):

```
PPCG Holiday Punch.

Ingredients.
408 ml apple cider
404 ml ginger beer
416 ml champagne
67 ml unsweetened cranberry juice
4 pinches mixed spice

Method.
Put apple cider into the mixing bowl.
Divide mixed spice into the mixing bowl.
Put ginger beer into the mixing bowl.
Divide mixed spice into the mixing bowl.
Put champagne into the mixing bowl.
Divide mixed spice into the mixing bowl.
Put unsweetened cranberry juice into the mixing bowl.
Sift the mixed spice.
Pour contents of the mixing bowl into the baking dish.
Sift the mixed spice until sifted.

Serves 5.

```

Try it online!

# Answer
> 6 votes
# ArnoldC, 107 bytes

```
IT'S SHOWTIME
TALK TO THE HAND "ArnoldCArnoldCArnoldCArnoldCArnoldCArnoldCArnoldC"
YOU HAVE BEEN TERMINATED

```

Try it online!

# Answer
> 5 votes
# Python 3, 17 bytes

```
print("Python"*6)

```

Try it online!

Of course, Python 2 is 2 bytes shorter with

```
print"Python"*6

```

Try it online!

But I prefer Python 3

# Answer
> 5 votes
# Whispers, 36 bytes

```
> "Whispers"
> 8
>> 1×2
>> Output 3

```

Try it online!

Trivial question, trivial answers.

# Answer
> 5 votes
# \>\<\>,  ~~23 19 15 13~~  12 bytes

```
"><>" |o<.0l

```

Try it online!

Emigna saved 4 bytes. Not a tree saved another 3. Teal pelican managed to save 1 more byte. Thanks to all who have helped golfing! Citing Arnauld, with slight modifications: *I now have 15 seconds of experience in \>\<\> programming. So, this may actually be golfable*.

# Answer
> 5 votes
# ,,,, 6 bytes

```
',9i×

```

Try it online!

Hehe...

# Answer
> 5 votes
# , 3 bytes

```
31317403

```

Try it online!

Format similar to Hello World program, except output mode is `3` (Byte-per-three-commands). The three commands `131` encodes value `131` base 6 = `37` base 16 = character 7. Then `3` prints the character.

# Answer
> 5 votes
# Starry, 146 bytes

```
        + +*`        + +  * +  *       +* .                + +  * +          + * + .       + * +          + +* +  *        + * . . . .      + * +'

```

Try it online!

It looks prettier with decoration, though (180 bytes):

```
        + +*`
+ + /| * +  *       +
* .| \__
  + \__/+  * +__
     + * + . /  \
+ * +      ========
  + +* +  *  \__/
  + * . . . .      +
* +'

```

Try it online!

# Answer
> 4 votes
# Commentator, 316 bytes

```
           {-     {-    -}!  {-{- e#-}//{-#-}-}! {-
;{-
     {-   -}!!  -}////{-#{-#-}    {-     -}!-}//-}//e#   e#-}//     -}//-}//{-e#                   e#-}-}//e#      e#-}//-}//-}//-}//e#         e#{-e# e#{-e# e#{-e#         e#-}-}-}-}-}
;{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*{-/*-}-}-}-}-}-}-}-}-}-}-}

```

Try it online!

Not quite as long as my Verbosity answer, but getting there

# Answer
> 3 votes
## MSM, 9 bytes

```
..;;..MSM

```

Stack trace:

```
. . ; ; . . M S M             -- concat
  . ; ; . . M MS              -- concat
    ; ; . . MSM               -- dup
      ; . . MSM MSM           -- dup
        . . MSM MSM MSM       -- concat
          . MSM MSMMSM        -- concat
            MSMMSMMSM

```

# Answer
> 3 votes
# D, 20 bytes

```
auto f(){return"D";}

```

Try it online!

# Answer
> 3 votes
# , 3 bytes

```
"I"

```

Try it online!

# Answer
> 3 votes
# Emoji, 33 bytes

```
Emoji6➡

```

Abuses the type system. A lot. May not work on other interpreters than the Python one. It probably won't.

Try it online!

# Answer
> 3 votes
# Aceto, 16 bytes

```
o"pp
tkpp
ecp
"A

```

Try it online!

# Answer
> 3 votes
# Funky, 16 bytes

```
print("Funky"*5)

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
•äƵí•h6×R

```

Try it online!

---

0xE1BA50, encoded in base 255, decoded into hexadecimal, repeated 6 times, reversed.

# Answer
> 2 votes
# Japt, ~~8~~ 7 bytes

```
4ç"Japt

```

Try it

# Answer
> 2 votes
# ;#\*, 420 bytes

```
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

```

Try it online! (uses ;#+ instead)

# Answer
> 2 votes
# , 9 bytes

```
\echo "K"

```

Try it online!

# Answer
> 2 votes
# uBASIC, 27 bytes

```
1FORI=1TO6:?"uBASIC";:NEXTI

```

This answer is pretty small, thanks to uBASIC's tokenizer being powered with a solution of magic in unicorn blood.

Try it online!

# Answer
> 2 votes
# sed, 10 bytes

```
isedsedsed

```

I hope two trailing newlines are OK :P

Try it online!

# Answer
> 2 votes
# itflabtijtslwi, 31 bytes

```
/I/itflabtijtslwi//J/IIIIIII/JJ

```

Try it online!

# Answer
> 2 votes
# Bubblegum, ~~14~~ 13 bytes

*Saved 1 byte thanks to @ovs*

```
00000000: 732a 4d4a ca49 4d2f cda5 1603 00         s*MJ.IM/.....

```

Try it online!

# Answer
> 2 votes
# Hexadecimal Stacking Pseudo-Assembly Language, 636 bytes

```
20002D4077FF00AAAA20006540000020006740000020006140000020007540000020006740000020006e40000020006140000020004c40000020002040000020007940000020006c40000020006240000020006d40000020006540000020007340000020007340000020004140000020002d40000020006f40000020006440000020007540000020006540000020007340000020005040000020002040000020006740000020006e40000020006940000020006b40000020006340000020006140000020007440000020005340000020002040000020006c40000020006140000020006d4000002000694000002000634000002000654000002000644000002000614000002000784000002000654000002000484000001400004277FF4099FF2000014077FF4299FF4077FF2277FF4277FF4077FF0377FF04000101AAAA

```

Try it online!

Formatted:

```
20002D4077FF00AAAA200065400000200067400000200061400000200075
40000020006740000020006e40000020006140000020004c400000200020
40000020007940000020006c40000020006240000020006d400000200065
40000020007340000020007340000020004140000020002d40000020006f
400000200064400000200075400000200065400000200073400000200050
40000020002040000020006740000020006e40000020006940000020006b
400000200063400000200061400000200074400000200053400000200020
40000020006c40000020006140000020006d400000200069400000200063
400000200065400000200064400000200061400000200078400000200065
4000002000484000001400004277FF4099FF2000014077FF4299FF4077FF
2277FF4277FF4077FF0377FF04000101AAAA

```

## Explanation

```
; initialize 77 with 0x002D (45)
20 002D
40 77 (FF)

; label AAAA
00 AAAA

; print out the text
20006540000020006740000020006140000020007540000020006740000020006e40000020006140000020004c400000200020400000
20007940000020006c40000020006240000020006d40000020006540000020007340000020007340000020004140000020002d400000
20006f40000020006440000020007540000020006540000020007340000020005040000020002040000020006740000020006e400000
20006940000020006b40000020006340000020006140000020007440000020005340000020002040000020006c400000200061400000
20006d400000200069400000200063400000200065400000200064400000200061400000200078400000200065400000200048400000
140000

; decrement
    ; move counter to stack 99
        42 77 (FF)
        40 99 (FF)
    ; push 1 to 77
        20 0001
        40 77 (FF)
    ; move counter to stack 77
        42 99 (FF)
        40 77 (FF)
    ; subtract
        22 77 (FF)

; duplicate
42 77 (FF)
40 77 (FF)

; terminate if counter is 0
03 77 (FF)
04 (0001)

; redo
01 AAAA

```

# Answer
> 2 votes
# Standard ML (MLton), ~~55~~ ~~54~~ 46 bytes

```
val s="Standard ML";s^s^s;print(it^it^it^s^s);

```

Try it online!

### Output:

```
Standard MLStandard MLStandard MLStandard MLStandard MLStandard MLStandard MLStandard MLStandard MLStandard MLStandard ML

```

---

### Previous version: (55 bytes)

```
"Standard ML";print(concat(map(fn _=>it)(explode it)));

```

Try it online! (No worries, the code is harmless, eventhough it contains `explode it`.)

### Explanation:

`"Standard ML";` binds the string to the implicit value identifier `it`. We then `explode it` to convert the string into a list of characters and `map` a function `fn _=>it` over the list which replaces each character with the string. `concat` combines the list of strings to a single string and `print` outputs the resulting string.

# Answer
> 2 votes
# Hodor, 38 bytes

```
hodor.hod("HodorHodorHodorHodorHodor")

```

It's actually shorter than the pure Javascript equivalent!

Try it online!

# Answer
> 2 votes
# Java 11, 19 bytes

```
v->"Java".repeat(4)

```

Try it online.

# Java 8, 21 bytes

```
v->"JavaJavaJavaJava"

```

Well...

Try it here.

# Answer
> 2 votes
# brainfuck, ~~125~~ 119 bytes

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

```

First BF, I think it's still golfable but it may be a bit BF to golf BF ;)

Explanation:

```
+++++++++                        (_009  000  000  000  000)
[
 >+++++++++++                    ( 009 _011  000  000  000)
 [
  >+++++++++                     ( 009  011 _009  000  000)
  [
   >+>+<<-                       ( 009  011 _008  001  001)
  ]                              ( 009  011 _000  009  009)
  >>+<<<-                        ( 009 _010  000  009  010)
 ]                               ( 009 _000  000  099  110)
 >>-.                            ( 009  000  000 _098  110) Output: b
 >++++.                          ( 009  000  000  098  114) Output: r
 <-.                             ( 009  000  000 _097  114) Output: a
 ++++++++.                       ( 009  000  000 _105  114) Output: i
 >----.                          ( 009  000  000  105 _110) Output: n
 <---.                           ( 009  000  000 _102  110) Output: f
 >+++++++.                       ( 009  000  000  102 _117) Output: u
 <---.                           ( 009  000  000 _099  117) Output: c
 ++++++++.                       ( 009  000  000 _107  117) Output: k
 >[-]<[-]<<<-                    (_008  000  000  000  000)
]                                (_000  000  000  000  000)

```

-6 for removing redundant clear commands

Try it online!

# Answer
> 2 votes
# Sinclair ZX81/Timex TS1000/1500 BASIC, ~33 tokenized BASIC bytes for the listing

```
 LET A$="BASIC"
 1 FOR I=SGN PI TO LEN A$
 2 PRINT A$;
 3 NEXT I

```

Enter the language name into the `var stack` using direct mode to save one BASIC line, and save bytes in the listing itself. I assume the `A$` variable is five bytes for the string and two bytes for the pointer, but I'm not 100% sure how the this works on the `ZX81` \- I will find out and update the byte count.

### Sinclair ZX81/Timex TS1000/1500 BASIC (non-dynamic solution) ~21 tokenized BASIC bytes (symbolic listing)

```
 LET A$="BASIC"
 1 PRINT A$;A$;A$;A$;A$

```

Using the same technique as above, entering the `A$` variable in direct mode and then simply printing the string five times. To run either solution, don't use the command `RUN` or the `var stack` is initialised. Use:

```
 GOTO 1

```

# Answer
> 2 votes
# PHP (9 bytes)

```
PHPPHPPHP

```

Try it online

# Answer
> 2 votes
# TI-BASIC, 16 bytes

```
"TI-BASIC
Disp Ans,Ans
Ans

```

Alternatively (19 bytes):

```
For(I,1,3
Disp "TI-BASIC
End

```

# Answer
> 2 votes
# Befunge-93, 27 Bytes

Edit: Much cleaner solution ~~of the same length~~ suggested by James Holderness

```
0"39-egnufeB">:#,_$1+:9`#@_

```

Try It Online

Old 30 byte version:

```
?
_g7-00p"39-egnufeB">:#,_g`#@

```

Try It Online

It feels weird to use the ? command for something that isn’t random, but that’s the only direction changing instruction that had an ASCII value low enough

# Answer
> 2 votes
# Bash, 14 bytes

```
echo bash{,,,}

```

Try it online!

# ksh, 12 bytes

```
echo ksh{,,}

```

Try it online!

# sh, 10 bytes

```
echo sh{,}

```

Try it online!

Although, for 9 bytes, I can just do `echo shsh`.

# Answer
> 2 votes
# Underload, 28 bytes

```
(Underload)::::::::********S

```

Try it online!

# Answer
> 1 votes
# Jelly, 7 bytes

```
“¢³ƒ»ẋ5

```

Try it online!

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

```
L,"Add++"5*

```

Try it online!

# Answer
> 1 votes
# Pyth, 7 bytes

```
*4"Pyth

```

My first Pyth answer!

Thanks to Mr. Xcoder for a neat trick.

Try it online!

# Answer
> 1 votes
# PHP, ~~27~~ ~~21~~ 20 bytes

First PHP solution; thanks to everyone who helped out with this. Obviously, I'm not quite ready to start golfing in PHP yet!

```
<?=str_pad(P,9,HPP);

```

Try it online

(Yes, `<?="PHPPHPPHP";` or just `PHPPHPPHP` are shorter but they felt *far* too trivial.)

* Thanks to Dennis for some tips on PHP, which also saved a byte.
* Thanks to NieDzejkob for saving a further 5 bytes.
* Thanks to Titus for saving me a byte and teaching me something new abut PHP.

# Answer
> 1 votes
# APL,  ~~10~~ 7 bytes

```
∊(⍴c)⍴⊂c←⎕

APL => APLAPLAPL

```

previous answer above prompted for screen input but if no input is required then we have the trivial for 7 bytes

```
9⍴'APL'

```

# Answer
> 1 votes
# C++,  ~~24~~  22 bytes

*Thanks to @Quentin for saving two bytes!*

```
[]{return"C++C++C++";}

```

Try it online!

# Answer
> 1 votes
# Husk, ~~8~~ 6 bytes

```
‼D¨Ż%k

```

-2 bytes thanks to @Zgarb!

Try it online or alternatively `DD¨Ż%k` would work too..

### Explanation

```
‼D¨Ż%k
  ¨Ż%k  -- compressed string: "Husk"
‼D      -- duplicate twice: "HuskHuskHuskHusk"

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 30 bytes

```
 OUTPUT =DUPL('SNOBOL4',7)
END

```

Try it online!

# Answer
> 1 votes
# Deorst, 11 bytes

```
'Deorst'l6*

```

Try it online!

# Answer
> 1 votes
# PHP, 59 bytes

Not the best way to do it (and there's a better php solution), but here's my go at it:

```
<?php $s="php";$l=strlen($s);for($i=0;$i<$l;$i++){echo $s;}

```

Try it online!

# Answer
> 1 votes
# rk, 22 bytes

```
rk:start
print: "rkrk"

```

Try it online!

# Answer
> 1 votes
# Octave, 26 bytes

```
disp(repmat('Octave',1,6))

```

Try it online!

# Answer
> 1 votes
# MY-BASIC, 33 bytes

```
for x=1 to 8
print"MY-BASIC"
next

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
"05AB1E"6×

```

Try it online!

# Answer
> 1 votes
# Befunge-98 (FBBI), 22 bytes

```
7v
"<_@#:-1,k6"Befunge

```

Try it online!

with `-98` included:

```
av
"<_@#:-1,k9"Befunge-98

```

Try it online!

# Answer
> 1 votes
# pl, 4 bytes

```
plpl

```

Try it online!

# Answer
> 1 votes
# Cy, 12 bytes

```
"CyCy" print

```

Try it online!

# Answer
> 1 votes
# Clojure, ~~49~~ 37 bytes

*12 bytes saved thanks to @cliffroot*

```
(print(apply str(repeat 7"Clojure")))

```

Try it online!

# Answer
> 1 votes
# Perl 6,  ~~14~~  12 bytes

```
say 'Perl6'x 5

```

Try it

```
{'Perl6'x 5}

```

Try it (bare block lambda that returns a string)

Note that I have it output `Perl6` as *Perl 5* and *Perl 6* are at least as different as *C++* and *Java* are.

# Answer
> 1 votes
# Tcl, 14 bytes

```
puts TclTclTcl

```

Try it online!

# Answer
> 1 votes
# Charcoal, 10 bytes

```
×Charcoal⁸

```

Try it online! Alternatively, also 10 bytes:

```
×⁸Charcoal
Ｆ⁸Charcoal

```

More idiomatic for 13 bytes would be to say:

```
≔Charcoalθ⭆θθ
≔CharcoalθＦθθ

```

# Answer
> 1 votes
# Clean, 29 bytes

```
c="CleanCleanCleanCleanClean"

```

Because actually doing anything requires `import StdEnv`, it's shorter to just hardcode.

Try it online!

# Answer
> 1 votes
# JavaScript ES7, 30/41/43/33 bytes

Thanks @Shaggy for reducing the size of the second and 4th versions

### Boring repeat 10 times: 30 bytes

```
alert("JavaScript".repeat(10))
```

### Array mapping of a string: 41 bytes

```
alert([...x="JavaScript"].fill(x).join``)
```

### For loop: 43 bytes

```
for(i=j='';10>j++;i+="JavaScript");alert(i)
```

### Joining empty 11 element array: 33 bytes

```
alert(Array(11).join`JavaScript`)
```

# Answer
> 1 votes
# ReRegex, 17 bytes

```
a/ReRegex/aaaaaaa

```

Potentially one of the most simple ReRegex answers I've ever written.

Try it online!

# Answer
> 1 votes
# C, 20 bytes

```
main(){printf("C");}

```

Try it online!

# Answer
> 1 votes
## This=That, 57 bytes

```
a=This=That
i=0
while loop j=<9
a=print
while loop j=end

```

This does exactly what you think it does. The string stored to `a` is printed nine times, accomplished by the loop.

The idea I get from the Esolangs page is that that equals sign in the first line is part of the string literal, not an assignment operator.

Thanks to @FrownyFrog for pointing out an error.

# Answer
> 1 votes
# Bean, 15 bytes

### `xxd`-style hexdump:

```
00000000: 53d0 80a3 8100 2080 b525 3dc2 e5e1 6e    SÐ.£.. .µ%=Âåán

```

### JavaScript equivalent:

```
'Bean'.repeat(4)

```

Try it online!

# Answer
> 1 votes
# Ruby, 12 bytes

```
$><<"Ruby"*4

```

Because Kaiser Chiefs.

Try it online!

# Answer
> 1 votes
## T-SQL, ~~76~~ 67 bytes

```
declare @i char(5)='T-SQL',@ int=1 a:print @i set @+=1if(@<6)goto a

```

# Answer
> 1 votes
# Decimal, 52 bytes

```
13068101099105109097108D117D91D00D30101D111D42D591D5

```

Try it online!

Ungolfed / explanation:

```
13068101099105109097108D 117D   ; push "Decimal", push 17
91D                             ; create jump point 1
  00D 301 01D                   ; set DSI to 0 ("Bitwise"), print, set back to 1 (initially 7)
  111D 42D                      ; push 1, subtract from previous SI
5 91D 5                         ; if DSI truthy, jump to point 1

```

Fun fact that I just remembered: Decimal doesn't care about the "top of stack" like most stack-based esolangs; it instead operates on a "default stack index" that can be modified at will, allowing for rather easy stack manipulation.

# Answer
> 1 votes
# Brain-Flak, 229 bytes

```
((()()()()()){}){({}<(((((((((((((()()()){}){}()){}){}()){}()))<({}[(()()()()()){}])>())[(()()()){}])<(((((()()()()())){}{})){}{})>(()()()()){})[()()()()()])[(()()()()){}])((()()()()){}){}())(((((()()()()){}){}){}()){})>[()])}{}

```

Try it online!

This is 228 bytes of code, and `+1` for the `-A` flag.

# Answer
> 1 votes
# Scala 27 16 bytes

```
print("Scala"*5)

```

# Answer
> 1 votes
# Ruby, 10 bytes

```
p "ruby"*4

```

Try it online!

# Answer
> 1 votes
# JavaScript 58 54 bytes

```
a='',f=i=>i<9?(f(i+1),a+="JavaScript"):0;f(0);alert(a)

```

## Solution using `document.write` (57 53 bytes)

```
(f=i=>{i<9?f(i+1):0;document.write("JavaScript")})(0)

```

# Answer
> 1 votes
# Excel VBA, 22 Byte

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window

```
?[Rept("Excel VBA",9)]

```

# Answer
> 1 votes
# Swift, 30 bytes

```
for _ in 1...5{print("Swift")}

```

Try it online!

# Answer
> 0 votes
# Bitwise, 188 bytes

```
.SUB:
LABEL &1
NOT $1 *1
AND *1 $2 *2
XOR $1 $2 $1
SL *2 &1 $2
JMP @1 $2
RET $1
MOV 1 &7 &1
OUT &66 1
OUT &105 1
OUT &116 1
OUT &119 1
OUT &105 1
OUT &115 1
OUT &101 1
SUB 1 &1 1
JMP &-9 1

```

Try it online!

I can't golf the `.SUB` help D:

# Answer
> 0 votes
# C# Interactive, 44 bytes

```
for(int i=15;--i>0;)Write("C# Interactive");

```

Haven't found an online compiler, I did it with the C# Interactive REPL in VS 2017.

# Answer
> 0 votes
# Implicit, ~~16~~ ~~14~~ 12 bytes

```
Implicit":+7

```

Try it online!

```
Implicit       push character codes for I, m, p, l, i, c, i, t
        "      stringify stack
         :     duplicate top of stack
          +7   concatenate top of stack to previous 7 times
               implicit string output

```

# Answer
> 0 votes
# Excel Formula, 24

```
=REPT("ExcelFormula",12)

```

# Answer
> 0 votes
# shortC, 24 bytes

```
Da"shortC"
AJa a a a a a

```

Try it online!

```
Da"shortC"     // define variable a as string "shortC"
A              // main function
 J             // print string
  a a a a a a  // a, 6 times, auto-concatenated

```

# Answer
> 0 votes
# Julia, ~~24~~ 15 bytes

Minus 9 bytes thanks to SalchiPapa

```
print("Julia"^5)

```

Try it online!

# Answer
> 0 votes
# Eukleides, 37 bytes

```
e="Eukleides"
print e,e,e,e,e,e,e,e,e

```

Don't think it can be golfed down any further. While a list of strings can be printed, they can't be assigned to a variable without a `cat` operation. So, building a string of three "Eukleides"es and printing three of those blows up to 38 bytes:

```
e="Eukleides"
f=cat(e,e,e)
print f,f,f

```

Eukleides prints a newline after every `print` command. If the challenge allowed for newlines between instances of the language name then we could do this in 33 bytes:

```
for i=1to 9
print "Eukleides"
end

```

# Answer
> 0 votes
# VBA, 11 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window

```
?"VBAVBAVBA

```

# Answer
> 0 votes
# LOLCODE, 75 bytes

```
HAI 1.3
VISIBLE "LOLCODELOLCODELOLCODELOLCODELOLCODELOLCODELOLCODE"
KTHXBYE

```

Try it online!

# Answer
> 0 votes
# Pushy, 11 bytes

```
`Pushy\x5`:N"

```

Where `\x5` represents the literal byte `0x05`.

**Try it online!**

```
`Pushy\x5`      \ Push the character codes for 'Pushy', and a 5
          :     \ Pop the 5 and loop 5 times:
           N"   \ Output the rest of the stack, with no newline.

```

# Answer
> 0 votes
# Ruby, 12 bytes

```
$><<"Ruby"*4

```

# Answer
> 0 votes
# Bash, 83 bytes

For the whole version string:

```
while read -n1;do echo -n `bash --version|head -1`;done< <(bash --version|head -1)

```

Returns (on my machine):

```
GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)GNU bash, version 4.4.7(1)-release (x86_64-pc-linux-gnu)

```

# Answer
> 0 votes
# Excel, 15 Bytes

Anonymous worksheet function that takes no input and outputs to the calling cell

```
=REPT("Excel",5

```

This may be ported to Google Sheets for 24 Bytes

```
=REPT("Google Sheets",13

```

# Answer
> 0 votes
# Tomato, 14 bytes

```
"Tomato"YYYYYY

```

# Answer
> 0 votes
# Ruby: 10 chars

```
p 'ruby'*4

```

Result

```
rubyrubyrubyruby

```

# *Previous Implementation: 25 chars*

```
def x(y);p y*y.length;end

```

Simple invocation:

```
x('javascript')
 => "javascriptjavascriptjavascriptjavascriptjavascriptjavascriptjavascriptjavascriptjavascriptjavascript"

```

# Answer
> 0 votes
# Powershell, 15 bytes

```
"Powershell"*10

```

Very boring. But I can't think of any way to shorten it.

---
Tags: code-golf, string, kolmogorov-complexity
---


title: Is my number Unique

text:
# Question
Title: Is my number Unique
In this challenge we learned a way to encode every positive integer using factor trees.

Here is how it works:

* The empty string has value of 1.
* `(S)` where `S` is any expression with a value of **S** evaluates to the **S**th prime.
* `AB` where `A` and `B` are arbirary expressions with values of **A** and **B** respectively has value **A\*B**.

For example if we wanted to represent 7 we would do

```
  7 -> (4) -> (2*2) -> ((1)(1)) -> (()())

```

Turns out we can represent every whole number using this method. In fact some numbers we can represent in multiple ways. Because multiplication is commutative 10 is both

```
((()))()

```

and

```
()((()))

```

At the same time some numbers can only be represented in 1 way. Take 8 for example. 8 can only be represented as

```
()()()

```

And since all of our atoms are the same we can't use commutivity to reorganize them.

---

So now the question is "Which numbers can only be represented in 1 way?". The first observation is one I just started making back there. It seems that perfect powers have some special properties. Under further investigation we can find 36, which is 62 is a perfect power but has multiple representations.

```
(())()(())()
(())()()(())
()(())()(())
()(())(())()
()()(())(())

```

And this makes sense because 6 is already rearrangable, so any number we make out of 6 must also be rearrangable.

So now we have a rule:

* A number has a unique representation if it is a perfect power of a number with a unique representation.

That rule can help us reduce determining if a composite number is unique to determining if a prime number is unique. Now that we have that rule we want to figure out what makes a *prime* number unique. This is actually pretty self evident. If we take a unique number and wrap it in parentheses, the result must be unique, and, going the other way if **n** has multiple representations the **n**th prime must have multiple representations. This yields the second rule:

* The **n**th prime is unique if and only if **n** is unique.

Both of these rules are recursive, so we are going to need a base case. What is the smallest unique number? One might be tempted to say 2 because its just `()`, but 1, the empty string, is even smaller and is unique.

* 1 is unique.

With these three rules we can determine whether a number has a unique factor tree.

## Task

You may have seen it coming, but your task is to take a positive integer, and determine if it is unique. You should write either a program or function that does this computation. You should output one of two possible values, what these values are is up to you but one should represent "yes", being output when the input is unique and one should represent "no" being output otherwise.

Your answers should be scored in bytes with less bytes being better.

## Test cases

Here are the first couple unique numbers:

```
1
2
3
4
5
7
8
9
11
16
17
19
23
25
27
31

```

Suggested test cases

```
5381 -> Unique

```

It seems that OEIS A214577 is somehow related, so if you need more test cases try there, but I don't know they are the same so use at your own risk.

# Answer
# Husk, ~~11~~ 10 bytes

Saved one byte thanks to Zgarb!

```
Ωεo?oṗ←¬Ep

```

Returns `1` for unique, `0` otherwise

Try it online! Or returning the first 50

### Explanation:

```
Ωε              Until the result is small (either 1 or 0), we repeat the following
         p     Get the prime factors
  o?           If ...
        E      they are all equal:
    ȯṗ←           Get the index of the first one into the primes
               Else:
       ¬          Not the list (since non-empty lists are truthy, this returns 0)

```
> 9 votes

# Answer
# Jelly, 10 bytes

After a LOT of fiddling around!

```
ÆET0ṪḊ?µl¿

```

A monadic link taking a positive integer and returning `1` if it is unique or `0` if not.

**Try it online!**

### How?

```
ÆET0ṪḊ?µl¿ - Link: number, n     e.g. 11          or 13            or 20
         ¿ - while:
        l  - ...condition: (left) logarithm with base (right)
           -               note: x log 0 and x log 1 both yield None, which is falsey
       µ   - ...do the monadic chain: (first pass shown)
ÆE         -   prime exponent array   [0,0,0,0,1]    [0,0,0,0,0,1]    [2,0,1]
  T        -   truthy indexes         [5]            [6]              [1,3]
      ?    -   if:
     Ḋ     -   ...condition: dequeue (i.e. if length > 1)
   0       -   ...then: literal zero   -              -               0
    Ṫ      -   ...else: tail           5              6               -
           - end result                1              0               0

```

**Wait, logarithm, what?!**

Lets run through some examples of the loop.

If `n=31` (**311**, the eleventh prime):

```
log test # |  left, x |  right, b |  x log b
-----------+----------+-----------+----------
         1 |       31 |        31 |    1.000 -> continue
         2 |       11 |        31 |    0.698 -> continue
         3 |        5 |        11 |    0.671 -> continue
         4 |        3 |         5 |    0.683 -> continue
         5 |        2 |         3 |    0.631 -> continue
         6 |        1 |         2 |    0.000 -> stop, yielding left = 1

```

If `n=625` (**54**):

```
log test # |  left, x |  right, b |  x log b
-----------+----------+-----------+----------
         1 |      625 |       625 |    1.000 -> continue
         2 |        3 |       625 |    0.171 -> continue
         3 |        2 |         3 |    0.631 -> continue
         4 |        1 |         2 |    0.000 -> stop, yielding left = 1

```

If `n=225` (**52×32**):

```
log test # |  left, x |  right, b |  x log b
-----------+----------+-----------+----------
         1 |      225 |       225 |    1.000 -> continue
         2 |     *  0 |       225 |-inf+nanj -> continue
         3 |     ** 0 |         0 |     None -> stop, yielding left = 0

*The dequeued list was not empty
**Tailing an empty list in Jelly yields 0

```
> 7 votes

# Answer
# APL (Dyalog), 42 bytes

```
⎕CY'dfns'
{1≥⍵:1⋄1=≢∪r←3pco⍵:∇1+¯1pco⊃r⋄0}

```

Using `⎕CY'dfns'` with `dfns`es isn't very feasible on tio.
> 4 votes

# Answer
# Jelly, 11 bytes

```
ÆfẋE$ḢÆCµl¿

```

Try it online!

-2 thanks to a very genius trick by Jonathan Allan.

Using H.PWiz's Husk algorithm.
> 2 votes

# Answer
# Pari/GP, 49 bytes

```
f(n)=d=factor(n);n<2||(#d~<2&&f(primepi(d[1,1])))

```

Try it online!
> 1 votes

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