title: Total cost of The 12 Days of Christmas

text:
# Question
Title: Total cost of The 12 Days of Christmas
# Introduction

I have decided that this Christmas, as a "present" to a friend, I wish to purchase the things described in the classic song "The 12 Days of Christmas". The only problem is, I don't know how to calculate the total price!

# Your Task

Given a list of prices (in order from first to last), calculate the total price of all the items if they were ordered as described by the song. Remember, each item is ordered once more than the one before it, and this repeats for as many days as there are items!

## Example

The first few lines of the song:

> On the 1st day of Christmas, my true love gave to me
> A partridge in a pear tree
>
> On the 2nd day of Christmas, my true love gave to me
> Two turtle doves,
> And a partridge in a pear tree.
>
> On the 3rd day of Christmas, my true love gave to me
> Three French hens,
> Two turtle doves,
> And a partridge in a pear tree.
>
> \\$\vdots\\$

The song then continues, each day adding in a new present, with the number increasing each time (e.g. "4 calling birds", "5 gold rings", etc.). up to a total of 12 days.

Therefore, the total number of each item as the song continues for 12 days goes: 1 partridge on day 1, 2 partridges and 2 doves on day 2, 3 partridges, 4 doves, and 3 French hens on day 3, etc.

# Rules and Scoring

Your program should take as input a list of prices (which can be of any length), and calculate the total price in the manner described above. Programs which give me the wrong answer for their inputs will be disqualified. Shortest size in bytes wins!

# Examples

```
[20, 20, 20]: 200
[25, 10]: 70
[10, 25, 10, 75]: 550

```

# Example price table

Feel free to use this table to test your program. The correct output should be 51765.02.

| Item | Price |
| --- | --- |
| A partridge in a pear tree | 27.50 |
| A turtle dove | 25.00 |
| One French hen | 5.00 |
| One calling bird | 70.00 |
| A gold ring | 65.00 |
| One goose a-laying | 25.00 |
| One swimming swan | 500.00 |
| A milkmaid hired for 1hr | 4.25 |
| One lady dancing | 289.65 |
| One lord leaping | 318.26 |
| One piper piping | 100.83 |
| One drummer drumming | 100.13 |

Or, as a single list of prices:

```
[27.50, 25.00, 5.00, 70.00, 65.00, 25.00, 500.00, 4.25, 289.65, 318.26, 100.83, 100.13]

```

# Answer
> 17 votes
# 05AB1E, ~~4~~ 3 bytes

```
Œ˜O

```

Try it online!

sublists, flatten, sum.

I actually found this approach as I was trying writing an APL solution which ended up being almost identical to my answer for even-sum-subarrays.

# Answer
> 12 votes
# Jelly, ~~5~~ 4 bytes

```
JƤSḋ

```

Try it online!

-1 byte thanks to pxeger!

Ignores the strings as input, just takes a list of 12 prices

## How it works

Basically, the number of each item is given as

```
Day  1:  1
Day  2:  1  2
Day  3:  1  2  3
Day  4:  1  2  3  4
...
Day 12:  1  2  3  4  5  6  7  8  9 10 11 12
Total : 12 22 30 36 40 42 42 40 36 30 22 12

```

Which is just the prefixes of the range `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]`, summed down the columns. We then multiply each price by the quantity and take the total

```
JƤSḋ - Main link. Takes a list of 12 prices P on the left
 Ƥ   - Over the prefixes of P:
J    -   Convert to a length range
  S  - Sums of the columns
   ḋ - Dot product with P

```

# Jelly, 3 bytes

```
ẆFS

```

Try it online!

A port of ovs' answer \- sublists, flatten, sum

# Answer
> 9 votes
# JavaScript (ES6), 35 bytes

Expects an array of prices.

```
a=>a.map(v=>t+=p+=v*++i,i=t=p=0)&&t

```

Try it online!

# Answer
> 8 votes
# Julia 1.0, 26 bytes

```
!x=sum(cumsum(x.*keys(x)))

```

Try it online!

# Answer
> 8 votes
# Excel, ~~52~~ ~~69~~ 59 bytes

Saved 10 bytes thanks to MarcMush pointing out how Excel interprets empty cells when doing math.

```
=SUM(LET(n,COUNT(A:A)+1,s,SEQUENCE(n),IFNA(A:A*s*(n-s),0)))

```

Input is in the range `A:A`.

* `LET(n,COUNT(A:A)+1` defines `n` to be one more than the number of cells in the range `A:A` that are a number. Why we need it to be one *more* will be clear later.
* `LET(~,s,SEQUENCE(n)` defines `s` to be a vertical array of numbers 1 to the value of `n` we just defined. This is a list of how many of each gift is given at a time. 1 partridge, 2 doves, 3 hens, etc. (Lots of birds...)
* `(n-s)` is best explained with an example. If there are 12 entries, this is `(13-[1-13])` which becomes `([12-0])` which is how many days each gift is given. IE, the first gift is given on all 12 days and the 13th gift is given on 0 days because the list isn't that long.
* `A:A*s*(n-s)`, then, is `(Value of each gift) * (number of times that gift is given on each day) * (number of days a gift is given)` which is, therefore, a list of the total value of each gift item over all the days.
* `IFNA(~,0)` accounts for the fact that the calculation above fails when the cell is empty because a number times an empty string is an error for Excel. This turns those errors into zeros.
* `SUM(LET(~,IFNA(~)))` sums up all the values.

The screenshot below shows the last three steps in columns `C:E`.

# Answer
> 7 votes
# Ruby, ~~36~~ 30 bytes

```
->g{r=w=0;g.sum{|x|r+=x*w+=1}}

```

Try it online!

# Answer
> 7 votes
# , 33 bytes

Or **\>=4.1, 26 bytes** by replacing the word `function` with `\`.

```
function(p)(rev(n<-seq(p))*n)%*%p

```

Try it online!

# Answer
> 7 votes
# Pyth, 4 bytes

```
ss.:

```

Try it online!

15 bytes (ungolfed) to avoid floating point precision errors.

# Answer
> 6 votes
# Vyxal, 5 bytes

```
żḂ*Þ•

```

Try It Online!

Vyxal is able to do the times-reverse thing more efficiently than Jelly (because you need the `$` for chaining in Jelly, and Vyxal has a bifurcate command), but unfortunately it does not have 1-byte dot product like Jelly does, so the byte save gets canceled out.

Unfortunately (for me), caird+pxeger have found a 4-byter. I mean, I could pretty trivially get one by cheating:

# Vyxal `s`, 4 bytes

```
żḂ**

```

Try It Online!

but I'll try to figure something out.

# Vyxal, 4 bytes

```
ÞSf∑

```

Try it Online!

4 bytes by porting the same solution (ovs's) that everyone else is. Thanks to lyxal for finding this.

# Vyxal `d`, 2 bytes

```
ÞS

```

Try it Online!

Flag abuse for the win. Credit to Aaroneous Miller.

# Answer
> 5 votes
# Jelly, 4 bytes

```
ḋƤJS

```

Try It Online!

-1 byte thanks to caird coinheringaahing

# Answer
> 5 votes
# C (gcc), ~~54~~ 53 bytes

```
d;f(x,n)float*x;{for(*x*=d=n;--d;)*x+=~d*(d-n)*x[d];}

```

Try it online!

*Saved a bytes thanks to ceilingcat!!!*

Inputs the list of prices as a pointer to an array along with its length (because pointers in C carry no length info).
Returns the total cost in the first element of the array.

# Answer
> 4 votes
# APL+WIN, 16 bytes

Prompts for prices.

```
+/(n×⌽n←⍳⍴v)×v←⎕

```

Try it online! Thanks to Dyalog Classic.

# Answer
> 4 votes
# Husk, 3 bytes

```
ΣΣQ

```

Try it online!

Uninventive port of ovs's O5AB1E answer: upvote that one instead.

# Answer
> 4 votes
# Perl 5 \+ `-p`, 15 bytes

Using the insight from @Arnauld's answer.

```
$\+=$x+=$_*$.}{

```

Try it online!

---

# Perl 5 \+ `-pa`, 26 bytes

```
$\+=(@F-$-++)*$_*$-for@F}{

```

Try it online!

# Answer
> 4 votes
# x86 32-bit machine code, 23 bytes

```
d9 ee 31 c0 dd 04 c2 40 50 0f af c1 50 da 0c 24 de c1 58 58 e2 ee c3

```

Following the `fastcall` calling convention, takes the length in ECX and the address of an array of double-precision floating-point numbers in EDX, and returns the result on the FPU register stack.

Try it online!

Assembly:

```
.text
.global dayscost
.intel_syntax noprefix
dayscost:
    fldz                         # Push 0 onto the FPU register stack, for a running total.
    xor eax, eax                 # EAX = 0, for the current day number.
repeat:
    fld QWORD PTR [edx+8*eax]    # Push the new item's price onto the FPU register stack.
    inc eax                      # Add 1 to EAX. It is now the 1-indexed day number.
    push eax                     # Push EAX onto the regular stack.
    imul eax, ecx                # Multiply EAX by the number of remaining days.
    push eax                     # Push the product onto the regular stack.
    fimul DWORD PTR [esp]        # Multiply the price by that product.
    faddp                        # Add the full product to the running total.
    pop eax                      # Pop the product from the regular stack.
    pop eax                      # Pop to restore the day number in EAX.
    loop repeat                  # Repeat, counting down the number of remaining days in ECX.
    ret                          # Return.

```

# Answer
> 3 votes
# Python 3, ~~69~~ ~~64~~ ~~61~~ 55 bytes

Takes a list of floats as input.

```
lambda l:sum(o*-~c*(len(l)-c)for c,o in enumerate(l))

```

Try it here!

# Answer
> 3 votes
# Fortran, 116 bytes

Try it Online.

```
real,allocatable::A(:),s;read*,n
allocate(A(n));read*,A
do i=1,n;do j=1,i;s=s+A(j)*j
enddo;enddo
print'(f0.2)',s
end

```

Another demo of our old friend, Fortran (emphasis on old). Elegance, simplicity and flexibility are not words that spring to mind. The requirement to allow `n` inputs forced me to write those chunky `allocate` statements.

# Answer
> 2 votes
# Pari/GP, 27 bytes

```
a->Pol((x*Ser(a))'/y=1-x)%y

```

Try it online!

See the input as a polynomial \\$A=\sum\_{i=0}^{n-1}a\_ix^i\\$. The derivative of \\$A\ x\\$ is \\$(A\ x)'=\sum\_{i=0}^{n-1}(i+1)\ a\_ix^i\\$. So \\$(A\ x)'/(1-x)=\sum\_{i=0}^{n-1}(\sum\_{j=0}^{i}(j+1)\ a\_j)x^i+O(x^n)\\$. Then we only need to take the first \\$n\\$ terms and evaluate it at \\$x=1\\$.

# Answer
> 2 votes
# SimpleTemplate 0.84, 86 bytes

This full program expects a variable number of arguments passed to the `render()` method. Argument unpacking can be used for convenience. Each argument is 1 gift.

```
{@eachargv}{@inc__}{@set*__ __,argc}{@set*_ __,_}{@incby_ T}{@incby-1argc}{@/}{@echoT}

```

The result is displayed on standard output, by default.

This works the same way as @caird coinheringaahing answer in Jelly.
However, everything is done manually, to obtain the `Total` row on the table.

---

## Ungolfed:

The code above looks like gibberish, so, bellow is an ungolfed version of it:

```
{@set total 0}

{@each argv as value key key}
    {@inc by 1 key}

    {@set* key key, argc}
    {@set* value key, value}

    {@inc by value total}
    {@inc by -1 argc}
{@/}

{@echo total}

```

Yeah ... It still looks like gibberish...

---

## About the language:

There are a few important things to notice here:

* Plenty of whitespace isn't mandatory.
`{@eachargv}` and `{@each argv}` do the same.
* The line `{@set total 0}` isn't golfed to `{setT 0}`: it was removed because the `{@incby_ T}` will define the variable `T`.
* The line `{@each argv as value key key}` is golfed into `{@eachargv}`.
By default, the `{@each}` loop uses the variable `_` for the value and `__` for the key, if none were provided.
This allows skipping all the "fluff" after `argv`.
* `{@inc by 1 key}` and `{@inc__}` increment the `key` (or `__`) variable by 1. Due to rubbish math support, this has to be done.
* `{@set*__ __,argc}` and `{@set* key key, argc}` both multiply the `key` variable by `argc`.
The variable `argc` contains the length of the `argv` variable.
This will calculate the number of times that the current gift was gifted on all 12 days.
This should be `1 * 12`, `2 * 11`, `3 * 10` ... (`(key + 1) * argc`).
* `{@set*_ __,_}` and `{@set* value key, value}` will multiply the `key` variable by the `value`, and save it into the `value` variable.
* `{@incby_ T}` and `{@inc by value total}` will increment the `total` by the `value` calculated before.
* `{@incby-1argc}` and `{@inc by -1 argc}` will decrement the `argc` variable by 1.
This variable, initially, has the length of the `argv` array.
At the end, the value will be `0`.
* `{@echoT}` and `{@echo total}` will display the total.

Yeah ... Very confusing...

---

## Running the code:

You can run the code on: http://sandbox.onlinephpfunctions.com/code/b775fddea1ae9c869962f893ac915c8087cb779a

Please pick a version between 5.6 and 7.4.13. Can't fix the 8.0.0 compatibility issue without invalidating this answer.

# Answer
> 2 votes
# IBM/Lotus Notes Formula Language, 102 bytes

```
Z:=L:=@Elements(i);T:=0;C:=1;@For(X:=1;X<=L;X:=X+1;@Set("T";T+i[X]*Z*C);@Set("Z";Z-1);@Set("C";C+1));T

```

There is no online interpreter for Notes so here is a screenshot of the expected output:

After more years than I can remember working with Lotus Notes and several posts on here, this will probably be my last Formula Language post as our company has just decommissioned the last Notes application that I was responsible for and my designer client will most likely soon be removed.

The end of an era. RIP, LN.

# Answer
> 2 votes
# TI-Basic, 9 bytes

```
sum(cumSum(AnscumSum(1 or Ans

```

Takes input in `Ans`. Output is stored in `Ans` and displayed. Does not work for empty lists as TI-Basic does not support them.

# Answer
> 2 votes
# Zsh, 65 bytes

Try It Online.

```
A=($@)
for i ({1..$#})for j ({1..$i})((s+=A[j]*j))
printf %.2f $s

```

Had to use `printf` to fix the output - Zsh arithmetic gives a funky result of `51765.019999999982` otherwise

# Answer
> 2 votes
# convey, 33 bytes

Dude, i love convey

```
v<-1
12"0<
{**+@}
1">>^
^"=12
^+1

```

Try it online!

The start of the process:

# Answer
> 1 votes
# Charcoal, 13 bytes

```
ＩΣＥθ×ι×⊕κ⁻Ｌθκ

```

Try it online! Link is to verbose version of code. Explanation: Port of my golf to @GingerIndustries' Python answer.

```
   θ            Input list
  Ｅ             Map over prices
     ι          Current price
    ×           Multiplied by
        κ       Current index
       ⊕        Incremented
      ×         Multiplied by
           θ    Input list
          Ｌ     Length
         ⁻      Minus
            κ   Current index
 Σ              Take the sum
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 1 votes
# Rust 137 Bytes

```
fn r(v: Vec<f64>)->f64{let mut c=0.;let k=v.len()as f64;let s=v.iter().map(|x|{c+=1.;x*c*(k-c+1.)}).collect::<Vec<f64>>();s.iter().sum()}

```

Try it out!

# Answer
> 1 votes
# Python 3, ~~145~~ 137 bytes

```
p=list(map(eval,input().split()))
n=len(p)
d=1
t=0
for x in range(12):
 t=t+p[d-1]*d*(12-(d-1))
 d+=1
print(t)

```

Try it online!

# Answer
> 1 votes
# Python 2, 64 bytes

```
i=input()
t,c,l=0,1,len(i)
for x in i:t+=x*l*c;l-=1;c+=1
print t

```

Try it online!

Python 2 because it will directly take the list as input and saves 1 byte by not needing the brackets for `print`.

# Answer
> 1 votes
# Scratch, 223 bytes

Try it online!
Alternatively, 23 blocks

```
when gf clicked
delete all of[S v
repeat until<(answer)=[F
add(answer)to[S v
ask[]and wait
end
set[I v]to[-1
set[T v]to[
repeat(length of[S v
change[I v]by(1
repeat((length of[S v])-(I
change[T v]by((I)*(item((I)+(1))of[S v

```

## Explanation

```
when gf clicked         Initiates code
delete all of[S v        Clears the "Shopping" list
repeat until<(answer)=[F  Loops code until the user inputs "F"
add(answer)to[S v          Adds user's input to the "Shopping" list
ask[]and wait               Prompts the user to give input
end                           Marks the end of code to be looped
set[I v]to[-1                   Resets the Item being accounted for
set[T v]to[                       Resets the Total cost of the items
repeat(length of[S v                Loops code for each item on the list
change[I v]by(1                       Increments the Item to be checked
repeat((length of[S v])-(I              Loops code for each day the item is purchased
change[T v]by((I)*(item((I)+(1))of[S v    Adds (item cost * quantity) to the total

```

# Answer
> 1 votes
# APOL, 63 bytes

```
v(1 s(i));v(2 []);f(⌬(¹) a(2 x(x(+(∈ 1) I(∋)) -(l(¹) ∈))));⊕(²)

```

# Answer
> 1 votes
# Haskell, 69 bytes

```
f x=sum$map sum[(map$uncurry(*))$zip x[1..n]|n<-[1..genericLength x]]

```

Try it online!

# Answer
> 1 votes
# Japt `-x`, 3 bytes

```
ã c

```

Try it

```
ã c     :Implicit input of array
ã       :Subsections
  c     :Flatten
        :Implicit output of sum of resulting array

```

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


title: Accessories after the fact!

text:
# Question
Title: Accessories after the fact!
This challenge is inspired by Mathematics is fact. Programming is not.

---

The mathematical notation for a factorial, or a **fact** is an exclamation mark **`!`**. The exclamation mark is also a common symbol for **`not`** in many programming languages.

### Challenge:

Take a string, containing numerals, and the characters: **`+ !`** as input and output the following:

Everything in front of an exclamation mark should be evaluated as a mathematical expression, so `2+2` would be `4`.

Everything after a single exclamation mark should be appended as accessories to whatever is in front of it, so: `2+2!5` should give `45`, because `2+2=4`, and `5` is an accessory. `2+2!5+5` should give `410`.

Since `!` also means `not`, anything that's **not** an accessory after the fact should **not** be appended. So, `2+2!!5` should give `4`, since `5` is not an accessory. Now, `not(not(true))==true`, so `2+2!!!5` should give `45`. `2+2!!5!5+5` should give: `410`, because `2+2=4`, then followed by a factorial and `!5!5+5`. The first `5` is not a fact, but `5+5` is after another exclamation mark, and is therefore a fact, yet again.

**Clarifications:**

* The exclamation marks will not be adjacent to a **`+`** on either side.
* There will not be leading `+` for numbers (it's `5`, not `+5`).
* You may optionally include a leading zero if that's the result of the expression in front of the first `!`. Both `4` and `04` are accepted output for input: `0+0!4`

**Executive summary:** evaluate each sum (treating `!` as separators). Then discard all numbers that appear after an even number of `!` (counting from the start of the string). Then remove all `!`.

**Test cases:**

```
!
   <- Empty string

5
5

12!
12

!87
87

!!5
   <- Empty string

5+5!2+2
104

5+5!!2+2
10

1!2!3!4!5!6!7!8!9
12468

10+10!!2+2!!3+3!4+4
208

2!!3!5
25

2!!3!5!7
25

10!!!!!!!5
105

```

**This is so the shortest code in bytes (in each language) wins!** Explanations are strongly encouraged!

# Answer
## Retina, ~~35~~ ~~31~~ 29 bytes

Saved 4 bytes by taking some inspiration from ETHproductions.

Thanks to Leo for saving another 2 bytes.

```
\d+|\+
$*
1+
$.&
1`!

!\d*!?

```

Try it online!
> 6 votes

# Answer
## JavaScript (ES6), ~~58~~ 56 bytes

Saved two bytes thanks to Martin Ender.

```
let f =
x=>x.replace(/[^!]+/g,eval).replace(/!(\d*)!?\d*/g,"$1")
```

```
<input value="2+2!5+5" oninput="try{O.value=f(value)}catch(e){}"><br>
<input id=O value="410" disabled>
```

Might be improved somehow...
> 5 votes

# Answer
# Jelly, 18 bytes

```
ṣ”!µḊm2;@ḢW$LÐfVṾ€

```

**Try it online!**

### How?

```
ṣ”!µḊm2;@ḢW$LÐfVṾ€ - Main link: string
ṣ”!                - split on '!' characters
   µ               - monadic chain separation (call that x)      e.g. ['1+1','0+0','0+0','0+0','','1+0','','','']
    Ḋ              - dequeue x (all but the leftmost entry of x) e.g.       ['0+0','0+0','0+0','','1+0','','','']
     m2            - modulo 2 index into that result             e.g.       ['0+0',      '0+0',   '1+0',   '']
           $       - last two links as a monad
         Ḣ         -     head x (the leftmost entry of x)        e.g.  '1+1'
          W        -     wrap                                    e.g. ['1+1']
       ;@          - concatenate with reversed arguments         e.g. ['1+1','0+0',      '0+0',   '1+0',   '']
             Ðf    - filter keep:
            L      -     length (keep that have non-zero length) e.g. ['1+1','0+0',      '0+0',   '1+0']
               V   - eval as jelly code (vectorises)             e.g. [  2,    0,          0,       1]
                      Yes, addition is just + and decimal numbers are just strings of digits in Jelly believe it or not!
                Ṿ€ - uneval €ach (creates a string from each one)e.g. [ '2',  '0',        '0'     ,'1']
                      without the € it would uneval the list and hence yield commas too)
                   - implicit print (prints the resulting list [of characters and possibly
                      lists of characters] as if it were all one string.)

```
> 2 votes

# Answer
# Jelly, 16 bytes

```
ṣ”!µḢW;m2$VṾ$L¡€

```

Try it online!

## Explanation

The key observation here is that we can run the steps "out of order"; instead of evaluating the sums then ignoring the ones we don't like, we can ignore the sums in invalid positions, then evaluate the rest.

```
ṣ”!µḢW;m2$VṾ$L¡€
ṣ”!                Split input on '!'
   µ               Set as the new default for missing arguments
    Ḣ              Take the first element, removing it from the default
     W;  $         Cons with
       m2            every odd-numbered element of {the tail of the !-split input}
               €   For each remaining element
          VṾ$      Evaluate and de-evaluate it
             L¡      a number of times equal to its length

```

Evaluating a sum like `"10+10"` will evaluate it to a number, e.g. `20`, then de-evaluate it to a string, `"20"`. Repeating that process has no additional effect (it's idempotent). Thus, we effectively evaluate every element of the string, *except* the null string, which remains unevaluated because it has a zero length.
> 2 votes

# Answer
# Python 3, 90 bytes

```
def f(s,e=1,r=''):
 for x in s.split('!'):
  if x:r+=str(eval(x))*e
  else:e=1-e
 return r

```

Try it online!

* -8 thanks to 97.100.97.109
* -1 thanks to Steffan

### Explanation

```
def f(s,e=1,r=''):

```

Define a function, `f`, which takes in a string, `s`.

`e` is whether to evaluate the next expression, and `r` is the return string.

```
 for x in s.split('!'):

```

Iterate through the string, split by `'!'`s.

```
  if x:r+=str(eval(x))*-e

```

If `x` is not empty, and `e` is True, evaluate `x` and add to the return string.

```
  else:e=1-e

```

Otherwise, set `e` to `not e`

```
 return r

```

Return the final value of `r`

---

# Python 3.8+, 74 bytes

```
lambda s,e=1:''.join(e*str(eval(x))for x in s.split('!')if x or(e:=1-e)*0)

```

(Suggested by 97.100.91.109)

Attempt this online!
> 2 votes

# Answer
## CJam, 20 bytes

```
r'!/{_{'+/1b}&}%(\2%

```

Try it online! (Linefeed-separated test suite.)
> 1 votes

# Answer
# Ruby, ~~58~~ 56+1 = ~~59~~ 57 bytes

Uses the `-p` flag. -2 bytes from Tutleman.

```
i=0;$_=' '+$_;gsub(/!?([^!]*)/){eval$1if(2>i+=1)||i%2<1}

```

Try it online! (An extra line of code was added so that it would take all of the input lines and print the output in different lines.)
> 1 votes

# Answer
# Pip, 18 bytes

I think this is the shortest it gets... although I said that about three iterations ago too.

```
{VaX++v%2+!v}Ma^'!

```

Takes input as command-line argument. Try it online!

### Explanation

```
                    a is 1st cmdline arg; global variable v is -1 (implicit)
              a^'!  Split a on !
{           }M      Map this function to the resulting list (note that inside function,
                    a is the function arg):
    ++v              Increment v (so that v tracks the 0-based index of the current
                     element)
       %2            We want to keep the elements where v%2 is 1...
         +!v         ... and also v=0, where v%2 is 0, but adding !v makes it 1
  aX                 String-multiply the argument by the above quantity (turning elements
                     we don't want into empty string)
 V                   Eval it (eval'ing empty string gives nil, but that's okay because
                     nil doesn't output anything)
                    Autoprint the resulting list, concatenated together (implicit)

```
> 1 votes

# Answer
## Batch, ~~192~~ 184 bytes

```
@echo off
set/ps=
call:c . "%s:!=" "%"
echo(%s%
exit/b
:c
set s=
if not %2=="" set/as=%2
:l
shift
shift
if "%1"=="" exit/b
if %1=="" goto l
set/at=%1
set s=%s%%t%
goto l

```

Having to handle the empty strings is inconvenient.
> 0 votes

# Answer
# R, 95 bytes

```
function(x)for(e in strsplit(gsub('!([^!]*)![^!]*','\\1!',x),'!')[[1]])cat(eval(parse(text=e)))

```

There is probably some room for improvement but at the moment it is the best I can come up with.
> 0 votes

# Answer
# Japt `-P`, 14 bytes

```
q'! kÏ©YvÃ£OxX

```

Try it

You can also Try all test cases, with a slight modification in the footer since the `-mR` flag that is used to run on multiple test cases conflicts with the `-P` flag that formats the output in the main version.

```
q'! kÏ©YvÃ£OxX
q'!            # Split the string on "!"
    k    Ã     # Remove elements where:
     Ï         #  The index is non-zero
      ©Yv      #  And the index is divisible by 2
          £    # For each remaining element:
           OxX #  Evaluate it as Javascript
-P             # Concatenate the elements and print

```
> 0 votes

---
Tags: code-golf
---


title: A multidimensional strategy challenge

text:
# Question
Title: A multidimensional strategy challenge
The wizard is determined to pose the most challenging challenge yet for which he believes the previous solution techniques will not work. He decides to go multidimensional.

If there is a number line with \\$x = 10\\$ then your task is to prove this. If you do so you win. In this situation, for your code to be correct, it must correctly identify at least one such number line.

As before, the wizard will not let you choose a number larger than \\$9\\$. This might still be OK as you might still find 10 points and in fact the only way to win is to have found all 10 points with values 9 or less on one of the number lines.

Your goal is to devise a strategy to play at the minimum expected cost. You should report your mean cost. To reiterate, your code should always find a line with 10 points less than or equal to 9 if one exists.

# Score

The score for your code is the expected cost to run it to completion. The lower the score the better.

# Answer
# Python 3 (PyPy), score = 3615.3653049197464

```
def f(w):
    for i in range(100):
        x = w.guess(i, 1.7858708219134063)
        if (6 <= x <= 7) or (x >= 2 and w.guess(i, 4.818513589137271) >= 6): w.guess(i, 9)

print(Wizard().use(f))

```

Try it online!

Try it online! (exact)
> 2 votes

# Answer
# R / Rcpp: 3531.3 ± 1.803

On average, the policy accrues ~3042.27 from searching number lines, and ~489 from resetting. Evaluated on 15 million simulated games. Bounds are a 95% bootstrap confidence interval with 10,000 iterations.

## Method

The policy generated for this problem was learned using the same genetic algorithm that I used in my solution to Strategy: The cunning cousin witch. You can find a more detailed description of the method and policy representation there.

The difference is that for this problem I learned two policies simultaneously. For each set of 100 number lines, the first policy was active during number lines 1 - 89, and the second policy was active during number lines 90 - 100. This gave the first policy an opportunity to search more optimally early in the set of number lines, while the second policy could focus on controlling the risk of needing a new set of number lines.

## Learned Policies

The first policy is active for the first 89 number lines, attempts to minimize the cost of searching. On average, this policy passes on 2.00 number lines that would have been possible to complete per episode.

The first policy is approximately

$$ \begin{bmatrix} 0.00 & 1.80\\ 0.50 & 0.00\\ 2.30 & 1.66\\ 3.44 & 2.10\\ 3.46 & 2.24\\ 4.76 & 2.41\\ 5.45 & 9.00\\ 7.37 & 9.00\\ 7.77 & 9.00\\ 9.00 & 3.32\\ \end{bmatrix} $$

The second policy is active during the last 11 number lines, and searches the number line more aggressively in order to offset the additional cost of not completing the game in time. On average, this policy passes on 1.11 number lines that would have been possible to complete per episode.

The second policy is approximately

$$ \begin{bmatrix} 0.00 & 2.96\\ 0.76 & 0.40\\ 1.84 & 0.98\\ 3.31 & 1.30\\ 3.08 & 1.00\\ 4.60 & 9.00\\ 9.00 & 9.00\\ 6.21 & 9.00\\ 6.06 & 9.00\\ 6.79 & 2.14\\ \end{bmatrix} $$

## Gene Importance

To better interpret the policies, it is useful to be able to measure how much each of the genes in those policies contributes to the overall score. For this problem, the matrix representing a policy is a chromosome, and each matrix address is a gene.

The problem of how to assign a fixed contribution to each gene can be thought of as a cooperative game because each gene's contribution to the overall score is mediated by all the other genes in the chromosome.

For an example of how genes affect each other, notice that in the second policy, \\$p\_{2}\\$, that \\$p\_{2}(1, 1) = 0.40\\$. Because \\$p\_{2}(0, 1) = 2.96 \> 0.76 = p\_{2}(1, 0)\\$, the policy will never search the number line using \\$p\_{2}(1, 1)\\$. We may say that \\$p\_{2}(1, 1)\\$ has a contribution of zero since it is never used, but that is only because of the joint relationship between \\$p\_{2}(0, 1)\\$ and \\$p\_{2}(1, 0)\\$. A better option might be to assign the contribution of \\$p\_{2}(1, 1)\\$ jointly to both \\$p\_{2}(0, 1)\\$ and \\$p\_{2}(1, 0)\\$. But how much total to each?

To solve this problem I calculated the contribution of each gene using Shapley additive values (SHAP values). Relevant to this problem, SHAP values have the property that the sum of all gene contributions equals the chromosome's total value, and that each gene's SHAP value equitably accounts for the conditional relationships between all the other genes.

The SHAP values for both policies are shown below compared against a trivial policy that searches the number line in units of one. The interpretation of an address in the SHAP value matrix, \\$s(x, y)\\$, is, "Replacing address \\$p(x, y)\\$ in the trivial policy with its value in the learned policy changes the policy's total score by \\$s(x, y)\\$ on average."

The SHAP value matrix for the first policy is approximately

$$ \begin{bmatrix} -0.53 & -318.01\\ 148.98 & -0.75\\ -1.04 & -10.96\\ 0.69 & -48.22\\ -2.68 & -86.70\\ -28.58 & -65.90\\ -51.29 & -239.74\\ 17.75 & -357.69\\ -3.87 & -258.72\\ 0.39 & -67.08\\ \end{bmatrix} $$

The SHAP value matrix for the second policy is approximately

$$ \begin{bmatrix} 0.49 & -19.24\\ 9.60 & 4.60\\ 6.43 & 2.90\\ -0.21 & -3.16\\ -0.55 & -1.97\\ -4.93 & -27.43\\ 11.70 & -52.22\\ -1.75 & -37.09\\ 16.48 & -27.57\\ 39.71 & -4.86\\ \end{bmatrix} $$

Recall that these SHAP values are in comparison to the trivial policy of searching in units of one, not to a random policy. Given that the score of the trivial policy is about 4994.913, and the sums of both SHAP matrices are about -1373.944 and -89.07059 respectively, adding the values together gives 4994.913 - 1373.944 - 89.07059 = 3531.898, which is nearly the score we get from evaluating the learned policy directly.

Note: Because this is a minimization problem, more negative SHAP values are better since they represent a decrease in total cost.

## Code

The code used to run the genetic algorithm is nearly equivalent to my solution linked at the top of this answer, so here I include only the code used to define the algorithm itself where it differs from my previous implementation.

**Rcpp code to Define the Genetic Algorithm**

```
//* Generate Chromosome
// [[Rcpp::export]]
NumericVector generateChromosome() {
  NumericVector chrom (40);
  for(int i = 0; i < 20; i++){
    if(i == 0 | i == 10){
      chrom[i] = 0;
    } else {
      chrom[i] = chrom[i - 1] + Rcpp::runif(1, 0.0, 2.0)[0];
    }
  }
  for(int i = 20; i < 40; i++){
    chrom[i] = Rcpp::runif(1, 0.0, 2.0)[0];
  }
  return(Rcpp::clamp(0.0, chrom, 9.0));
}

//* Chromosome to Policy
// [[Rcpp::export]]
NumericMatrix chromToPolicy(NumericVector x) {
  NumericVector policy = clone(x);
  policy[0] = 0.0;
  policy.attr("dim") = Dimension(20, 2);
  return(as<NumericMatrix>(policy));
}

//* Evaluate Chromosome
//* Note: The cost of resetting (1000) isn't hardcoded here
//* Instead, the number of resets per episode is counted
//* The cost penalty is applied in a chromosome fitness function instead
// [[Rcpp::export]]
NumericMatrix evaluatePolicy(
    NumericVector x,
    int iters,
    int maxCost = -1
) {

  //Convert chromosome to policy
  NumericMatrix policy = chromToPolicy(x);

  //Run episodes
  NumericMatrix out (iters, 6);
  bool earlyStop = false;
  for(int i = 0; i < iters; i++){

    //Initialize values
    NumericVector points = setPoints();
    double lineSearched = 0;
    int ptsFound = 0;
    int lineCount = 1;
    int polNum = 0;

    //Begin episode
    bool done = false;
    while(!done) {

      //Step forward if in policy
      if(policy(ptsFound + polNum, 0) >= lineSearched){
        lineSearched += policy(ptsFound + polNum, 1);
        if(lineSearched > 9){
          lineSearched = 9;
        }
        out(i, 0) += pow(2, lineSearched);
        ptsFound = sum(points <= lineSearched);

      } else {

        //Otherwise, reset
        //Code result
        if(sum(points <= 9) == 10){
          out(i, 4) += 1;
        } else {
          out(i, 2) += 1;
        }

        //Reset values
        points = setPoints();
        lineSearched = 0;
        ptsFound = 0;

        //Increase line count
        lineCount += 1;
        if(lineCount == 101){
          lineCount = 1;
          polNum = 0;
          out(i, 1) += 1;
        } else {
          //Integer division -> floor(lineCount / 10)
          if(lineCount / 10 + 1 > 9){
            polNum = 10;
          }
        }

      }

      //Reset when line searched but fewer than 10 points found
      if(lineSearched == 9 & ptsFound < 10){

        //Code result
        out(i, 3) += 1;

        //Reset values
        points = setPoints();
        lineSearched = 0;
        ptsFound = 0;

        //Increase line count
        lineCount += 1;
        if(lineCount == 101){
          lineCount = 1;
          polNum = 0;
          out(i, 1) += 1;
        } else {
          //Integer division -> floor(lineCount / 10)
          if(lineCount / 10 + 1 > 9){
            polNum = 10;
          }
        }

      }

      //Exit conditions
      if(ptsFound == 10){
        out(i, 5) += 1;
        done = true;
      }

      //Early stop condition
      if((maxCost >= 0 & out(i, 0) >= maxCost)){
        out(i, 0) = NA_REAL;
        earlyStop = true;
        done = true;
      }

    }
    if(earlyStop){
      break;
    }
  }

  //Return
  return(out);

}

```

**R Code for the SHAP Algorithm**

<pre><code># Characterize trivial policy
trivChrom <- c(0:9, 0:9, rep(1, 20))
trivOut <- evaluatePolicy(trivChrom, 15000000, 1000000)
trivOut <- mean(trivOut[, 1] + 1000 * trivOut[, 2])

# Characterize full policy
x <- readRDS(r"minPolicy_3472_121.rds")
evOut <- evaluatePolicy(x, 15000000, 1000000)
evOut <- mean(evOut[, 1] + 1000 * evOut[, 2])

# Initialize parameters
tol <- 5
iters <- 500

# Shapley algorithm
shapVals <- rep(0, length(x))

t <- 0
while(TRUE){

  # Increment t
  t <- t + 1

  # Permute the gene order
  geneOrder <- sample(1:length(x), length(x), replace = FALSE)

  # Calculate shap value
  shapPol <- trivChrom
  v <- rep(NA, length(x) + 1)
  v[1] <- trivOut
  for(j in 1:length(x)){
    if(abs(evOut - v[j]) < tol){
      v[j + 1] = v[j]
    } else {
      shapPol[geneOrder[j]] = x[geneOrder[j]]
      shapEv = evaluatePolicy(shapPol, 100000, 10000000)
      shapEv = mean(shapEv[, 1] + 1000 * shapEv[, 2])
      v[j + 1] = ifelse(is.na(shapEv), v[j], shapEv)
    }
    shapVals[geneOrder[j]] = (t - 1) / t * shapVals[geneOrder[j]] + (1 / t) * (v[j + 1] - v[j])
  }

  # Exit conditions
  if(t >= iters){
    break
  }

}
```
</code></pre>
> 2 votes

# Answer
# Python, average cost = 3498 +/- 5

Shamelessly steals the policy from Renaldi (thanks!), but always applies it to the number line with the highest probability of having 10 points instead of going through them one at a time. I tried to incorporate the backup policy, but that ended up making things worse. I'm not sure why my Gittin's Index answer doesn't work very well; I guess some assumption must be subtly violated or I have a bug somewhere.

```
import heapq
import functools
import random

import numpy as np
from scipy.stats import binom

def logsumexp(x):
    m = x.max()
    return np.log(np.sum(np.exp(x - m))) + m

@functools.lru_cache(None)
def log_p_win(a, n):
    k = np.arange(n, 11)
    u = np.zeros(k.shape) if a == 0 else binom(k, a / 10).logpmf(n)
    d = binom(k - n, (9 - a) / (10 - a))
    t = np.zeros(11 - n)
    for i in range(11 - n):
        t[i] = logsumexp(u + d.logpmf(i))
    return t[-1] - logsumexp(t)

policy = [
    [0, 0.5, 2.3, 3.44, 3.46, 4.76, 5.45, 7.37, 7.77, 9],
    [1.8, 0, 1.66, 2.1, 2.24, 2.41, 9, 9, 9, 3.32],
]

while True:
    mean_cost = 0
    sse_cost = 0
    queue = []
    done = True
    trials = 0
    cost = 0
    while True:
        if done or not queue:
            if not done:
                cost += 1000
            lines = [
                [random.uniform(0, 10) for _ in range(random.randrange(11))]
                for _ in range(100)
            ]
            del queue[:]
            for i, _ in enumerate(lines):
                heapq.heappush(queue, (-log_p_win(0, 0), 0, 0, i))
        done = False
        v, n, a, i = heapq.heappop(queue)
        if a <= policy[0][n]:
            a = min(9, a + policy[1][n])
        else:
            continue
        cost += 2 ** a
        n = sum(1 for x in lines[i] if x <= a)
        if n == 10:
            done = True
            trials += 1
            d = (cost - mean_cost)
            mean_cost += d / trials
            sse_cost += d * (cost - mean_cost)
            if trials % 100 == 0:
                print(trials, mean_cost, np.sqrt(sse_cost) / trials)
            cost = 0
            continue
        if a == 9:
            continue
        v = -log_p_win(a, n)
        heapq.heappush(queue, (v, n, a, i))

```
> 2 votes

# Answer
# Python, score ~= 3922

Repurposes some of my code from the Witch challenge. Uses a Gittins Index strategy, where the cost of resetting is estimated empirically.

```
import heapq
import functools
import random

import numpy as np
from scipy.stats import binom

bound = 16153
samples = 50

g = np.linspace(0, 9, samples)

def logsumexp(x):
    m = x.max()
    return np.log(np.sum(np.exp(x - m))) + m

def init_trans(samples):
    print("computing transition matrix...\n")
    trans = np.full((samples, 10, samples, 11), float('-inf'))
    g = np.linspace(0, 9, samples)
    for i0 in range(samples - 1):
        print(f"computing row {i0} of {samples}", end='\r', flush=True)
        g0 = g[i0]
        for n in range(10):
            k = np.arange(n, 11)
            u = np.zeros(k.shape) if i0 == 0 else binom(k, g0 / 10).logpmf(n)
            for i1 in range(i0 + 1, samples):
                g1 = g[i1]
                d = binom(k - n, (g1 - g0) / (10 - g0))
                for m in range(n, 11):
                    v = d.logpmf(m - n)
                    trans[i0,n,i1,m] = logsumexp(u + v)
    print()
    trans -= trans.max(axis=-1, keepdims=True)
    trans = np.exp(trans)
    trans /= trans.sum(axis=-1, keepdims=True)
    return trans

trans = init_trans(samples)

@functools.lru_cache(None)
def gittins_value(i0, n0, v0):
    if n0 == 10:
        return (0, None)
    if i0 == samples - 1:
        return (v0, None)
    v = v0
    i = None
    for i1 in range(i0 + 1, samples):
        v1 = sum(trans[i0,n0,i1,n1] * (2 ** g[i1] + gittins_value(i1, n1, v0)[0]) for n1 in range(n0, 11))
        if v1 <= v:
            v = v1
            i = i1
    return (v, i)

@functools.lru_cache(None)
def gittins_index(i0, n0):
    low = 0
    high = bound
    best_action = i0 + 1
    while high - low >= 1e-9:
        mid = low + 0.5 * (high - low)
        v, i1 = gittins_value(i0, n0, mid)
        if v == mid:
            low = mid
        else:
            high = mid
            best_action = i1
    return high, best_action

mean_cost = 0
reset_cost = bound
queue = []
reset = True
trials = 0
cost = 0
while True:
    if reset:
        lines = [
            [random.uniform(0, 10) for _ in range(random.randrange(11))]
            for _ in range(100)
        ]
        del queue[:]
        for i, _ in enumerate(lines):
            heapq.heappush(queue, gittins_index(0, 0) + (i,))
    reset = False
    v, a, i = heapq.heappop(queue)
    if v > 1000 + reset_cost:
        cost += 1000
        reset = True
        continue
    cost += 2 ** g[a]
    n = sum(1 for x in lines[i] if x <= g[a])
    if n == 10:
        reset = True
        trials += 1
        mean_cost += (cost - mean_cost) / trials
        reset_cost += (cost - reset_cost) / (trials + 100)
        cost = 0
        print(trials, mean_cost)
        continue
    if a == samples - 1:
        reset = not queue
        continue
    heapq.heappush(queue, (gittins_index(a, n) + (i,)))

```
> 0 votes

---
Tags: code-challenge
---


title: Longest Increasing Substring

text:
# Question
Title: Longest Increasing Substring
Given a list of positive integers, write code that finds the length of longest contiguous sub-list that is increasing (not strictly). That is the longest sublist such that each element is greater than or equal to the last.

For example if the input was:

\\$\[1,1,2,1,1,4,5,3,2,1,1\]\\$

The longest increasing sub-list would be \\$\[1,1,4,5\]\\$, so you would output \\$4\\$.

Your answer will be scored by taking its source as a list of bytes and then finding the length of the longest increasing sub-list of that list. A lower score is the goal. Ties are broken in favor of programs with fewer overall bytes.

# Answer
> 7 votes
# Pyth, score 2 (8 bytes)

```
lefSIT.:

```

Try it here!

Code points `[108, 101, 102, 83, 73, 84, 46, 58]`. Another shorter solution, `leSI#.:` scores 3, but its code points are `[108, 101, 83, 73, 35, 46, 58]`, which are very close to a score of 1, actually. ~~Rearranging a bit may help~~ Nevermind, the substrings built-in is `.:` which cannot be rearranged, so the lowest score must be 2 if the program makes use of it.

### How?

```
lefSIT.:     Full program. Accepts either a list or a string from STDIN.
      .:     Substrings.
  f  T       Only keep those that are...
   SI        Sorting-Invariant.
le           Length of the last item.

```

# Answer
> 5 votes
# JavaScript (Node.js), ~~score 3, ~~53~~ 46 bytes~~ score 2, ~~51~~ 50 bytes

-7 bytes thanks @Arnauld

~~+5~~ +4 spaces in exchange of -1 score

```
a=> a.map($= p=n=>$=(p<=(p=n)?++ x:x=1)<$?$: x)&&$

```

Try it online!

Assumes non-empty input. 61 bytes if empty list must be handled. Score 2 still.

```
a=> a.map($= p=n=>$=(p<=(p=n)?++ x:x=1)<$?$: x)&& a.length&&$

```

Try it online!

...or 58 if returning `false` is allowed. Score 2 still.

```
a=> a.map($= p=n=>$=(p<=(p=n)?++ x:x=1)<$?$: x)&& a>[ ]&&$

```

# Answer
> 5 votes
# Haskell, score 2, ~~66~~ ~~64~~ ~~61~~ ~~60~~ 65 bytes

* -2 bytes thanks to Max Yekhlakov
* -1 byte thanks to nimi
* +5 bytes to handle the empty list

```
foldr1 max.g
g[]=[0]
g(x:y:z)|x>y=1: g(y:z)
g(_:y)|a:b<-g y=1+a:b

```

Try it online! (verifies itself).

I never thought I could get a score of 2 with Haskell, and yet here I am!

Function `g` computes the lengths of all the increasing substrings recursively. `foldr1 max.g` takes the maximum of those lengths (`foldr1 max` is equivalent to `maximum`, but with a lower score).

# Answer
> 4 votes
# Husk, 5 bytes, score = 2

```
00000000: bc6d 4cdc 14                   ▲mLġ≥

```

Try it online!

It's unlikely to get a score lower than 2 with Husk because `ġ`1 has a really high codepoint and there needs to be something before it to get the maximum and length. An attempt could be made with trying to use multiple functions but `\n` would be before any helper functions which has a really low codepoint so anything after it would create an increasing byte-sequence of at least length 2.

1: This seems like the best way to use for the comparison operators would need to follow the various split functions like  (`span`).

### Explanation

```
▲mLġ≥  -- example input: [1,1,2,1,1,4,5,3,2,1,1]
   ġ≥  -- group elements by geq: [[1,1,2],[1,1,4,5],[3],[2],[1,1]]
 mL    -- map length: [3,4,1,1,2]
▲      -- maximum: 4

```

# Answer
> 3 votes
# MATL, score 2, 13 bytes

```
d0< ~Y'w)X>sQ

```

Input can be:

* An array of numbers.
* A string enclosed with single quotes. Single quotes within the string are escaped by duplicating.

MATL uses ASCII encoding. The codepoints of the above code are

```
100, 48, 60, 32, 126, 89, 39, 119, 41, 88, 62, 115, 81

```

Try it online!

### Explanation

```
d     % Implicit input. Consecutive differences (of code points)
0<    % Less than 0? Element-wise. Gives true or false
      % Space. This does nothing; but it breaks an increasing substring
~     % Negate
Y'    % Run-length encoding. Gives array of true/false and array of lengths
w     % Swap
)     % Index. This keeps only lenghts of runs of true values
X>    % Maximum. Gives empty array if input is empty
s     % Sum. This turns empty array into 0
Q     % Add 1. Implicit display

```

# Answer
> 3 votes
# Retina 0.8.2, 40 bytes, score 3

```
\d+
$*
(?<=(1+)),(?!\1)
¶
T`1`_
^O`
\G,?

```

Try it online! Link includes itself as byte codes as input. Explanation:

```
\d+
$*

```

Convert to unary.

```
(?<=(1+)),(?!\1)
¶

```

Split on decreasing pairs.

```
T`1`_

```

Delete the digits.

```
^O`

```

Sort the commas in reverse order. (I would normally write this as `O^` but can't do that here for obvious reasons.)

```
\G,?

```

Count the longest comma run, and add one to include the final number.

# Answer
> 3 votes
# Japt `-h`, 6 bytes, score 2

Don't *think* a score of 1 is possible. Should work with strings & character arrays too.

```
ò>¹mÊn

```

Try it \- included test case is the charcodes of the solution.

---

## Explanation

```
ò          :Partition after each integer
 >         :  That's greater than the integer that follows it
  ¹        :End partition
   m       :Map
    Ê      :  Length
     n     :Sort
           :Implicitly output last element

```

# Answer
> 3 votes
# Pascal (FPC), score 2

111 bytes

```
var a,b,c,t:bYte;bEgIn repeat read(a); iNc(c); if a<b then c:=1; if c>t then t:= c;b:= a;until eOf;write(t)eNd.

```

Try it online!

Assumes non-empty input. Numbers are taken from standard input separated by spaces.

# Answer
> 3 votes
# Perl 6, score 2, 46 bytes

```
{my&g=1+*×*;+max 0,|[\[&g]] [ |@_] Z>=0,|@_ }

```

Try it online!

Handles the empty list. The original code was:

```
{my&g=1+*×*;+max 0,|[\[&g]] @_ Z>=0,|@_}

```

So only 5 extra bytes to reduce the score to 2.

Edit: Ah, I figured out how to remove the assignment, but then I can't get that score below 3 because of the `)]]`...

### Explanation:

```
{                                  }  # Anonymous code block
 my&g=     ;  # Assign to &g an anonymous Whatever lambda
      1+*×*   # That multiplies the two inputs together and adds 1
                            @_ Z  0,|@_   # Zip the list with itself off-set by one
                                >=        # And check if each is equal or larger than the previous
                                         # e.g. [5,7,7,1] => [1,1,1,0]
                    [\[&g]]  # Triangular reduce it by the function declared earlier
                          # This results in a list of the longest substring at each index
                          # e.g. [5,7,7,1] => [1,2,3,1]
            +max 0,|      # And return the max value from this list, returning 0 if empty

```

# Answer
> 2 votes
# Jelly, 8 bytes, score 2

There is probably a score 1 solution somehow...

```
IṠµṣ-ZL‘

```

**Try it online!**

Source code as a list of byte values:

```
[73, 205, 9, 223, 45, 90, 76, 252]

```

### How?

```
IṠµṣ-ZL‘ - Link: list of integers  e.g. [ 1, 1, 2, 1, 1, 4, 5, 3, 2, 1, 1]
I        - increments                    [ 0, 1,-1, 0, 3, 1,-2,-1,-1, 0]
 Ṡ       - sign                          [ 0, 1,-1, 0, 1, 1,-1,-1,-1, 0]
  µ      - start a new monadic chain (a low byte to stop score being 3)
    -    - literal minus one             -1
   ṣ     - split at                      [[0, 1], [0, 1, 1], [], [], [0]]
     Z   - transpose                     [[0, 0, 0], [1, 1], 1]
      L  - length                        3
       ‘ - increment                     4

```

# Answer
> 1 votes
# 05AB1E, score 3 (9 bytes)

```
Œʒ¥dP}éθg

```

Can most likely be a score of 2 somehow.

Code points of the program-bytes: `[140,1,90,100,80,125,233,9,103]` (two sublists of length 3: `[1,90,100]` and `[80,125,233]`)

Try it online.

**Explanation:**

```
Œ            # Sublists
 ʒ   }       # Filter by:
  ¥          #  Take the deltas
   d         #  Check for each whether the number is >= 0
    P        #  And check if it was truthy for all deltas
      é      # Then sort by length
       θ     # Take the last element
        g    # And take its length as result

```

# Answer
> 1 votes
# Powershell, score 3, 44 bytes

```
($args|%{$i*=$_-ge$p;$p=$_;(++$i)}|sort)[-1]

```

Test script:

```
$f = {

(
    $args|%{        # for each integer from argument list
        $i*=$_-ge$p # -ge means >=.
                    # This statement multiplies the $i by the comparison result.
                    # A result of a logical operator is 0 or 1.
                    # So, we continue to count a current sequence or start to count a new sequence
        $p=$_       # let $p stores a 'previous integer'
        (++$i)      # increment and return incremented as length of a current sequence
    }|sort          # sort lengthes
)[-1]               # take last one (maximum)

}

@(
    ,(4, 1,1,2,1,1,4,5,3,2,1,1)
) | % {
    $e,$a = $_
    $r = &$f @a
    "$($r-eq$e): $r"
}

```

Output:

```
True: 4

```

Explanation:

* The script takes integers as argument list (spaltting).
* Each integer maps by a function to legnth of `contiguous sub-list that is increasing (not strictly)`. Then the script sorts lengthes and take a last (maximum) `(...|sort)[-1]`.

---

## Powershell 6, score 3, 43 bytes

```
$args|%{$i*=$_-ge$p;$p=$_;(++$i)}|sort -b 1

```

Same as above. One difference: `sort -b 1` is shortcut for `sort -Bottom 1` and means 1 element from the end of sorted array. So we need not an index `[-1]`.

# Answer
> 1 votes
# Java (JDK), score 3, 94 bytes

```
a->{int m=0,p=0,x=0,i=0,n;while(i<a.length){n=a[i++];m=(p<=(p=n)?++x:(x=1)) <m?m:x;}return m;}

```

Try it online!

Port of my (with suggestions from Arnauld) JS answer. `etu` in `return` and `hil` in `while` make it impossible to golf to score 2.

`for` cannot be used here because:

* `;for` is ascending
* `for` cannot be used at the beginning of the lambda body (scope restrictions). It is possible to wrap it with `{}` but apparently using `while` saves bytes.

# Answer
> 1 votes
# Stax, score 3 (15 bytes)

```
Z|[F|]F:^!C_%|M

```

Run and debug it

# Answer
> 1 votes
# Python 2, ~~score 5, 87 bytes~~ score 2, ~~101~~ ~~93~~ ~~92~~ 101 bytes

```
lambda a,m=1,o=[1]:max(reduce(lambda B,c:[B[:-m]+[B[-m]+m],B+o][c[0]>c[m]],zip(a,a[m:]), o)) *(a>[ ])

```

Try it online!

Ooops! Thought this was code-golf first time through...

# Answer
> 1 votes
# Dyalog APL, score 2, 20 bytes

```
{⍵≡⍬:0⋄⌈/≢¨⍵⊂⍨1,2>/⍵}

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), score 3, 45 bytes

```
Max[Length/@SequenceCases[#,x_/;OrderedQ@x]]&

```

Try it online!

`SequenceCases` and `OrderedQ` by themselves give a score of 3, so the score can't be improved without changing the approach significantly.

# Answer
> 0 votes
**Kotlin, Score 6, 119 bytes**

```
 fun x(a : IntArray){var m=1;var k=0;var d=1;while(k<a.size-1){if(a[k]<=a[k+1])m++;else{if(d<m)d=m;m=1};k++};println(d)}

```

Try Online

Explanation

1. Step 1: Check for previous value to next value
2. Step 2: If previous value is less or equal then add plus 1 keep doing while condition is true
3. Step 3: check previous count with next count, keep highest count in variable d.

# Answer
> 0 votes
# Java (JDK), 126 bytes, Score 6

Golfed

```
private static int l(byte[] o){int m=0;int c=1;int p=0;for(byte i:o){if(m<c){m=c;}if(i>=p){p= i;c++;}else{c=1;p=0;}}return m;}

```

Ungolfed

```
private static int longest(byte[] input) {
    int maxc = 0;
    int consec = 1;
    int prev = 0;
    for (byte i : input) {
        if (maxc < consec) {
            maxc = consec;
        }
        if (i >= prev) {
            prev = i;
            consec++;
        }
        else {
            consec = 1;
            prev = 0;
        }
    }
    return maxc;
}

```

Input

```
[112, 114, 105, 118, 97, 116, 101, 32, 115, 116, 97, 116, 105, 99, 32, 105, 110, 116, 32, 108, 40, 98, 121, 116, 101, 91, 93, 32, 111, 41, 123, 105, 110, 116, 32, 109, 61, 48, 59, 105, 110, 116, 32, 99, 61, 49, 59, 105, 110, 116, 32, 112, 61, 48, 59, 102, 111, 114, 40, 98, 121, 116, 101, 32, 105, 58, 111, 41, 123, 105, 102, 40, 109, 60, 99, 41, 123, 109, 61, 99, 59, 125, 105, 102, 40, 105, 62, 61, 112, 41, 123, 112, 61, 32, 105, 59, 99, 43, 43, 59, 125, 101, 108, 115, 101, 123, 99, 61, 49, 59, 112, 61, 48, 59, 125, 125, 114, 101, 116, 117, 114, 110, 32, 109, 59, 125]

```

# Answer
> 0 votes
# Kotlin, Score 4, 67 bytes

```
{a:IntArray->var i=0;var p=0;a.map{if(it<p){i=0};p=it;(++i)}.max()}

```

Main idea is: Transform each integer to length of contiguous sub-sequences that is increasing (not strictly). Return maximum.

* `a.map{...}` \- for each integer in the array do
* `if(it<p){i=0}` \- if current integer is less then a previous integer, then reset counter
* `p=it` \- store current integer in the previous
* `(++i)` \- increment counter and return value of the expression
* `.max()` \- get maximun of all length

# Answer
> 0 votes
# Ruby, 64 bytes

```
->e{e.size.downto(1).find{|l|e.each_cons(l).find{|c|c==c.sort}}}

```

Try it online!

# Answer
> 0 votes
# Brachylog, score: 2 (8 bytes)

```
⊇L≤₁&sLl

```

Try it online!

This code, according to Brachylog’s code page, is the following string of char codes / integers:

```
[08, 4C, 03, 80, 26, 73, 4C, 6C]
[8, 76, 3, 128, 38, 115, 76, 108]

```

Which results in a score of 2.

### Explanation

```
⊇L         L is a sublist of the input (trying from longest to shortest)
  L≤₁       L is increasing
     &sL    L is also a contiguous sublist of the input
        l   Output the length of L

```

We need to use  to get the longest sublists first and then check that it is contiguous with `s`, because `s` does not try them longest first (see this Brachylog tip).

# Answer
> 0 votes
# Go, score 4, 172 bytes

```
type y=int
type x=[]y
func f(q x)y{l,o:=*new(x),*new(x)
for _,e:=range q{n:=len(o)
if n>0&&o[n-1]>e{if len(l)<n{l=o}
o=append(*new(x),e)}else{o=append(o,e)}}
return len(l)}

```

Attempt This Online!

I'm pretty sure this is the absolute minimum this bit of code can achieve, because `=int` is ascending in terms of value.

If you change `y` to be `rune`, and `x=[] y` you then get hung up on `\nfor`. Unless someone finds a way to make case-insensitive keywords in Go, then 4 is the minimum score.

---
Tags: source-layout, self-scoring
---


title: Longest alternating subsequence

text:
# Question
Title: Longest alternating subsequence
*inspired by Longest Increasing Substring*

## Task

Given a list of non-negative integers, output the length of its longest alternating subsequence.

An *alternating sequence* is a sequence of numbers which alternates between strictly increasing and strictly decreasing. `[]`, `[999]`, `[9, 1]`, and `[0, 5, 0, 3, 2, 4]` are examples of an alternating sequence, while `[0, 0]` and `[1, 3, 5]` are not.

A mathematical definition: A sequence \\$A = a\_1, a\_2, \cdots, a\_n\\$ is alternating if

* \\$a\_k \ne a\_{k+1}\\$ for \\$k = 1, 2, \cdots, n-1\\$, and
* \\$a\_k \< a\_{k+1} \Rightarrow a\_{k+1} \> a\_{k+2} \\$ and \\$a\_k \> a\_{k+1} \Rightarrow a\_{k+1} \< a\_{k+2}\\$ for \\$k = 1, 2, \cdots, n-2\\$.

If the input is `[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]`, the longest alternating subsequence is `[3, 1, 4, 1, 9, 2, 6, 3, 5]` and its length is 9. Note that the *subsequence* does not need to be contiguous.

## Scoring

The score of your answer is calculated as follows:

* Treat your source code as a list of bytes (or, if your language uses a non-256-char custom character set, the list of character codes within the character set).
    + If your language supports multiple encodings, you may use the one that gives the best score. However, the score and the code size must be calculated using the same encoding.
* Give it as input to your own program, and the output is your score.

The lowest score wins. Tiebreaker is shorter code in bytes.

## Test cases

```
[] => 0
[1] => 1
[1, 1] => 1
[9, 9, 9, 9, 9, 9, 9] => 1
[5, 10] => 2
[0, 1, 2] => 2
[5, 10, 10, 5] => 3
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] => 9
[1, 2, 2, 2, 3, 3, 4, 4, 5, 6] => 2
[2, 2, 1, 2, 5, 6, 6, 5] => 4

```

# Answer
# Python 3, score 16, \\$6.6 \times 10^{2073} \\$ bytes

```
exec(b"".fromhex(str(len(" "))))

```

Try it online!

The string `" "` above should actually be the number of spaces below, about \\$6.6 \times 10^{2073} \\$, but somehow Stack Exchange won't let me post the whole string and TIO won't run it.

```
6578656328272563252573272531303225272563252573272536312527256325257327253130382527256325257327253937252725632525732725313039252725632525732725393825272563252573272531303025272563252573272539372527256325257327253332252725632525732725313038252725632525732725343425272563252573272531313225272563252573272536312527256325257327253438252725632525732725343425272563252573272531313325272563252573272536312527256325257327253435252725632525732725343925272563252573272535382527256325257327253130382527256325257327253632252725632525732725393125272563252573272539332527256325257327253937252725632525732725313130252725632525732725313030252725632525732725333225272563252573272531303925272563252573272539372527256325257327253132302527256325257327253430252725632525732725313032252725632525732725343025272563252573272531303825272563252573272539312527256325257327253439252725632525732725353825272563252573272539332527256325257327253434252725632525732725313132252725632525732725343425272563252573272531313325272563252573272534312527256325257327253434252725632525732725343525272563252573272531323625272563252573272531303225272563252573272534302527256325257327253130382527256325257327253931252725632525732725343925272563252573272535382527256325257327253933252725632525732725343425272563252573272531313325272563252573272534342527256325257327253131342527256325257327253538252725632525732725363125272563252573272531303825272563252573272539312527256325257327253438252725632525732725393325272563252573272534312527256325257327253432252725632525732725343025272563252573272534302527256325257327253931252725632525732725313132252725632525732725343425272563252573272531313425272563252573272539332527256325257327253931252725632525732725313132252725632525732725363025272563252573272534382527256325257327253933252725632525732725343525272563252573272531313325272563252573272534312527256325257327253432252725632525732725343025272563252573272531313325272563252573272534352527256325257327253131342527256325257327253431252725632525732725363025272563252573272534382527256325257327253431252725632525732725343125272729

```

Repeating a character many times in a row doesn't affect the score because an alternating subsequence can't contain two consecutive equal values. So, the game becomes to write a low-scoring wrapper that decodes a huge string of spaces (or any character) into arbitrary code and executes it.

The ginormous number above corresponds to the following moderately-golfed code for the length of the longest alternating subsequence. Being an exponential-time algorithm, it's too slow to actually compute the result for the code itself with spaces de-duplicated.

**91 bytes**

```
f=lambda l,p=0,q=-1:l>[]and max(f(l[1:],p,q),-~f(l[1:],q,r:=l[0])*(([p,r][p<0]-q)*(q-r)<0))

```

Try it online!

The wrapper

```
exec(b"".fromhex(str(len(" "))))

```

takes the length of a string of spaces, converts it to a hexadecimal string, interprets pairs of hex values as base 256 ASCII to convert it to a bytestring, and executes the result. Its longest alternating subsequence has length 16, as can be checked by an efficient implementation like the last one here, compared to 66 for the direct 91-byte code. The filler character can be replaced with any low-ASCII character without affecting the score, and single versus double quotes has no effect.

Actually, you might notice that the length is converted to a base-10 string with `str()`, not hexadecimal. This byte-save makes the wrapper have fewer alternations, at the cost of only being able to generate code of ASCII values whose hex representation have no letters `a-f`.

Luckily, this still allows all of `exc('%0)`, which already suffice to run arbitrary Python 3 code, as shown by kzh. We could start by converting our payload code to this restricted format, but the result is very long -- it won't fit in my computer's memory. So, we "golf" this by taking advantage of also having access to all digits `0-9` and the letter `s`. A string, for example `ABC` with ASCII values `[65,66,67]`, is converted to:

```
exec('%c%%s'%65%'%c%%s'%66%'%c%%s'%67%'')

```

which uses string formatting with `%s` to perform concatenation in place of the banned `+`. This format only gives a linear blow-up with 91 bytes becoming 1037, though this could surely be improved.

Amusingly, I thought that the Sep 2022 breaking change to Python string-converting large numbers would make this overall submission invalid in up-to-date versions of Python without using a command-line flag -- that is, if we're pretending that code of length \\$6.6 \times 10^{2073} \\$ can run at all. But, the 2074 digits of the number of spaces falls under the cutoff of 4300 past which `str` now errors out.
> 7 votes

# Answer
# 05AB1E, score: ~~13~~ ~~12~~ 7 (~~23~~ ~~21~~ 10 bytes)

```
¥.±Igª¾Kγg

```

-1 score (and -2 bytes) taking inspiration from *@DominicVanEssen*'s Husk answer.
-5 score (and -11 bytes) by porting *@CursorCoercer*'s Pyth answer, so make sure to upvote him/her as well!

Try it online or verify all test cases.

The program has the following bytes, and using this as input in my own program results in `7` as its score.

**Explanation:**

`¾` is used instead of `0` and `γ` is used instead of `Ô` to improve the score. `¥` could alternatively be `ü-`; `I` could be `¹` or `s`; `ª` could be `š`; and  could be `0.S`, but with any of those changes the score will remain the same, and combinations of some of these changes will also retain the same score, or even increase it.

```
¥           # Get the deltas/forward-difference of the (implicit) input-list
 .±         # Get the signum of each (0 if 0; -1 if <0; 1 if >0)
   Ig       # Push the input-length
     ª      # Append it to the list
      ¾K    # Remove all 0s from the list
        γ   # Split the list into groups of equal adjacent items
         g  # Get the length to get the amount of groups
            # (which is output implicitly as result)

```
> 4 votes

# Answer
# Husk, ~~11~~ ~~13~~ 14 bytes, score ~~9~~ 6

*Edit: +2 bytes to fix bug that counted repeated identical elements (thanks to Bubbler for spotting)*
*Edit2: changed approach for +1 byte but reducing score by 3*

```
→OmöËεgfIẊo±-Ṗ

```

Try it online!

The codepoints of the program from the Husk code page are: `[8,80,110,248,239,157,104,103,74,212,112,22,46,207]`, giving a longest alternating subsequence of length 6 (try it).
The codepoints were calculated using this program.

```
  mö            # map over
             Ṗ  # all subsequences of input
    ËεgfIẊo±-   # calculating length if it's an alternating seqeunce,
                # or returning zero otherwise (see below),
 O              # sort the results,
→               # and return the last (largest) element.

         Ẋo     # map over all pairs of values
           ±-   # getting the sign of the difference,
       fI       # remove zeros,
      g         # and group adjacent equal values;
   Ë            # now, if all the groups
    ε           # have a length of at most 1
                # return the length +1
                # (this is the length of the alternating subsequence)
                # otherwise return zero

```
> 4 votes

# Answer
# Pyth, score: 7, (15 bytes)

```
+!!Qlr8-._M.+QZ

```

Try it online!

And as an added bonus it runs in `O(n)` time.

### explanation

```
           .+Q     difference between each pair of elements in the input
        ._M        map list to the sign of the elements
       -      Z    remove all zeros
    lr8            number of sequences of repeated elements
+!!Q               add 1 if input is non-empty

```
> 4 votes

# Answer
# Jelly, (12 bytes), score 4

```
I¹ƇṠŻạƝTL+JṂ

```

A monadic Link that accepts a list of non-negative integers and yields the length of the longest alternating subsequence.

**Try it online!** Or see the test-suite.

The bytes are: `74 130 145 206 211 212 151 85 77 44 75 180`
See it score itself

### How?

An alternating subsequence of maximal length can always be formed by taking the first element (if one exists) and appending the peaks and troughs, so the code calculates the length of that subsequence.

```
I¹ƇṠŻạƝTL+JṂ - Link: list of integers, A  e.g. [2,2,1,2,5,6,6,5]  OR  [4]  OR  []
I            - incremental differences (of A)  [0,-1,1,3,1,0,-1]      []       []
  Ƈ          - keep those for which:
 ¹           -   no-op                         [-1,1,3,1,-1]          []       []
   Ṡ         - sign                            [-1,1,1,1,-1]          []       []
    Ż        - prepend a zero                  [0,-1,1,1,1,-1]        [0]      [0]
      Ɲ      - for neighbours:
     ạ       -   absolute difference           [1,2,0,0,2]            []       []
       T     - truthy indices                  [1,2,5]                []       []
        L    - length                          3                      0        0
          J  - range of length (of A)          [1,2,3,4,5,6,7,8]      [1]      []
         +   - add (vectorises)                [4,5,6,7,8,9,10,11]    [1]      []
           Ṃ - minimum (empty list yields 0)   4                      1        0

```
> 3 votes

# Answer
# Vyxal, score 4, 8 bytes

```
¯±ꜝĠL$ß›

```

Try it Online!

Port of CursorCoercer's Pyth answer, so upvote that!

The bytes are `[212, 213, 222, 189, 76, 36, 14, 131]`.
> 3 votes

# Answer
# Brachylog, score: 12 (18 bytes)

```
⊇L{s₂ᶠ≠ᵐ}-ᵐṡᵐ↰₁∧Ll

```

Try it online!

This scores 12 according to @Arnauld’s deleted JS answer, it times out on my own code.

This code, according to Brachylog’s code page, is the following string of char codes / integers:

```
[08, 4C, 7B, 73, 81, 98, 1B, 9F, 7D, 2D, 9F, D0, 9F, 0F, 80, 01, 4C, 6C]
[8, 76, 123, 115, 129, 152, 27, 159, 125, 45, 159, 208, 159, 15, 128, 1, 76, 108]

```

### Explanation

```
⊇L                    L is a subset of the input
  L{s₂ᶠ≠ᵐ}            Get all contiguous sublists of 2 elements, which must be different
          -ᵐṡᵐ        Compute the signs of the subtraction of these sublists
              ↰₁      Get all contiguous sublists of 2 elements, which must be different
                ∧Ll   Output the length of L

```
> 2 votes

# Answer
# Nibbles, ~~9~~ 10.5 bytes (21 nibbles), score ~~7~~ 6

*Edit: +1.5 bytes but -1 score from fixing potential bug with empty input array, spotted by CursorCoercer*

```
+`$,$,`=|!$>>@~`$-@$*

```

The 10 bytes + 1 half-byte of the Nibbles program are `8d 7d 3d b9 99 3c 04 0d 79 43 a` (in decimal `141 125 61 185 153 60 4 13 121 67 10`), giving a longest alternating subsequence of length 6.
Note that Nibbles pads the saved program with a filler `6` nibble at the end for odd numbers of nibbles: this is not counted in the bytes of the program.

```
+`$,$,`=|!$>>@~`$-@$*
         !              # zip together
          $             # the input
           >>@          # and the input without its first element
              ~         # using the combined function
                 -$@    # subtract arg2 from arg1
               `$       # and get the sign
        |           *   # filter to keep only nonzero elements
      `=                # and combine adjacent equal elements
     ,                  # now get the length of this
+                       # and add
 `$                     # 1 if non-zero
   ,$                   # the length of the input

```
> 2 votes

# Answer
# Charcoal, 49 bytes, score ~~28~~ 24

```
≔¬¬θεＦε«≔⁰ζ≔§θζηＦθ«≔⁻›ηκ›κηδ≔κη¿∧⁻ζδδ«≔δζ≦⊕ε»»»Ｉε

```

Try it online! Link is to verbose version of code and includes the program's byte sequences using Charcoal's code page as sample input. Explanation:

```
≔¬¬θε

```

Start with a sequence of length `1` unless the input is empty.

```
Ｆε«

```

Don't try to measure the length of the sequence if the input is empty.

```
≔⁰ζ

```

Start with there not being a direction yet.

```
≔§θζη

```

Start with a copy of the first element of the sequence. (This uses the variable I just set to `0` because this avoids a double alternation.)

```
Ｆθ«

```

Loop over the elements of the sequence.

```
≔⁻›ηκ›κηδ

```

Calculate the direction between the previous and current element.

```
≔κη

```

Save the current element as the previous element.

```
¿∧⁻ζδδ«

```

If the direction is nonzero and has changed from the previous direction (tested in reverse order to avoid a double alternation), then...

```
≔δζ

```

... saved the new direction, and...

```
≦⊕ε

```

... increment the sequence length.

```
»»»Ｉε

```

Output the final sequence length.

The program will also work on string input (using the Unicode code points of the characters); the rearrangement of the condition actually avoided four alternations so its score is now ~~32~~ 28 when measured this way.

I looked into the possibility of renaming the variables but as far as I can tell my naming scheme was already optimal.
> 1 votes

---
Tags: array, subsequence, self-scoring
---


title: Output "Fit" numbers

text:
# Question
Title: Output "Fit" numbers
# "Fit Numbers"

Sam has a "brilliant" idea for compression! Can you help?

---

Here is a rundown of Sam's compression scheme. First take in a base 10 representation of any natural number strictly smaller than 2^16, and write it as a binary string without any leading zeros.
```
1 -> 1
9 -> 1001
15 ->1111
13 ->1101
16 -> 10000
17 -> 10001
65535 -> 111111111111111

```

Now replace any group of one or more zeros with a single zero. This is because the number has gotten leaner. Your binary string now will look like this.

```
1 -> 1 -> 1
9 -> 1001 -> 101
15 ->1111 -> 1111
13 ->1101 -> 1101
16 -> 10000 -> 10
17 -> 10001 -> 101
65535 -> 111111111111111 -> 111111111111111

```

Now you convert the binary string back to a base 10 representation, and output it in any acceptable format. Here are your test cases. The first integer represents an input, and the last integer represents an output. Note that some numbers do not change, and thus can be called "fit"

```
1 -> 1 -> 1 -> 1
9 -> 1001 -> 101 -> 5
15 ->1111 -> 1111 -> 15
13 ->1101 -> 1101 -> 13
16 -> 10000 -> 10 -> 2
17 -> 10001 -> 101 -> 5
65535 -> 1111111111111111 -> 1111111111111111 -> 65535
65000 -> 1111110111101000 -> 11111101111010 -> 16250

```

---

You may use any language, but please note that Sam hates standard loopholes. This is code golf so the code can be as short as possible to make room for the "compressed" numbers".

---

Note:This is NOT an acceptable compression scheme. Using this will promptly get you fired.

---

Citation-Needed: I do not take credit for this concept. This comes from @Conor O' Brien's blog here see this OEIS of fit numbers. https://oeis.org/A090078

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

```
b00¬:C

```

**Explanation**

```
b        # convert input to binary
 00¬:    # replace 00 with 0 while possible
     C   # convert to int

```

Try it online

Saved 2 bytes thanks to Adnan
> 10 votes

# Answer
# Bash + GNU utilities, 27

```
dc -e2o?p|tr -s 0|dc -e2i?p

```

Input read from STDIN.
> 13 votes

# Answer
## JavaScript (ES6), 41 bytes

```
n=>+`0b${n.toString(2).replace(/0+/g,0)}`

```
> 7 votes

# Answer
## Jellyfish, 20 bytes

```
p
d
# S
,1
*
\dbi
 2

```

Try it online!

## Explanation

* `i` is input.
* `b` converts it to binary (list of digits)
* `\d` with arguments `2` and the digit list applies `d` (binary digits to number) to every length-2 substring of the digit list.
* `*` takes signum of the results: 00 goes to 0, everything else to 1.
* `,1` tacks a 1 to the end, so the last digit is not lost.
* `# S` selects from `bi` those digits which have a 1 on the list computed above: those that are not the left halves of 00.
* `d` converts back to number, and `p` prints the result.
> 7 votes

# Answer
## Python 2, 36 bytes

```
f=lambda n:n and f(n/2)<<(n%4>0)|n%2

```

A direct recursive implementation with no base conversion built-ins or string operations. Less golfed:

```
f=lambda n:n and[f(n/2),n%2+2*f(n/2)][n%4>0]

```

When `n` is a multiple of 4, it ends in two 0's in binary, so we cut one by floor-dividing by 2. Otherwise, we split `n` into `(n%2) + 2*(n/2)`, leave the last binary digit `n%2` alone, and recurse on the other digits `n/2`.
> 6 votes

# Answer
# Bash (sed + bc), ~~60~~ ~~55~~ 43 bytes

```
echo $[2#`bc<<<obase=2\;$1|sed s/00\*/0/g`]

```

edit:

1. changed `sed -E 's/0+` to `sed 's/00*` and changed echo and pipe used to pass the value to bc with `<<<`.
2. Brilliant suggestion by @Digital Trauma!

example:

```
$ bash script.sh 65000
16250
$ bash script.sh 15
15
$ bash script.sh 9
5

```
> 5 votes

# Answer
# Python 3, ~~55~~, 50 bytes.

Saved 4 bytes thanks to Sp3000.

Pretty straightforward solution.

```
import re
f=lambda x:eval(re.sub('0+','0',bin(x)))

```
> 4 votes

# Answer
# MATL, ~~11~~ ~~9~~ 8 bytes

```
BFFOZtXB

```

This version works only in MATLAB since `strrep` in MATLAB can handle logical inputs. Here is a version that will work in Octave (9 bytes) (and thus the online interpreter) which explicitly casts the logical inputs to type `double`.

**Try it online**

**Explanation**

```
    % Implicitly grab input
B   % Convert decimal to binary
FF  % Create the array [0 0]
O   % Number literal
Zt  % Replaces all [0 0] with [0] (will replace any number of 0's with 0)
XB  % Convert binary to decimal
    % Implicitly display

```
> 4 votes

# Answer
# Perl 6,  ~~31~~  27 bytes

```
~~{:2(.base(2).subst(:g,/0+/,0))}~~
{:2(.base(2)~~{S:g/0+/0/})}
```

## Explanation:

```
-> $_ {
  # convert from base 2
  :2(

    # convert to base 2
    $_.base(2)

    # substitute
    .subst(
      :global,
      / 0+ /,  # all substrings made of 0s
      '0'      # with one 0
    )
  )
}

```

## Example:

```
my &fit-compress = {:2(.base(2)~~{S:g/0+/0/})}
say fit-compress 1;     # 1
say fit-compress 9;     # 5
say fit-compress 15;    # 15
say fit-compress 13;    # 13
say fit-compress 16;    # 2
say fit-compress 17;    # 5
say fit-compress 65535; # 65535
say fit-compress 65000; # 16250

# number created with ｢:2( [~] <0 1>.roll: 256 )｣
say fit-compress 80794946326210692074631955353531749442835289622757526957697718534769445507500
# 4240335298301026395935723255481812004519990428936918

```
> 4 votes

# Answer
## Actually, 14 bytes

```
├`'0;;+(Æ`Y2@¿

```

Try it online!

Explanation:

```
├`'0;;+(Æ`Y2@¿
├               bin(input) (automatically discards leading zeroes)
 `'0;;+(Æ`Y     call this function until the output stops changing:
  '0;;+           push "0", "00"
       (Æ         replace "00" with "0" in binary string
           2@¿  convert from binary to decimal

```
> 3 votes

# Answer
# Ruby, ~~35~~ 31 bytes

-2 bytes thanks to @Doorknob

```
->n{eval ("0b%b"%n).squeeze ?0}

```

See it on repl.it: https://repl.it/CnnQ/2
> 3 votes

# Answer
## Javascript (ES6), 40 bytes

```
n=>'0b'+n.toString(2).replace(/0+/g,0)-0

```
> 3 votes

# Answer
## PHP, 53 51 Bytes

```
<?=bindec(preg_replace("/0+/",0,decbin($argv[1])));

```

Takes an argument from the console.

## Thanks to:

@manatwork replace "0" with 0
> 2 votes

# Answer
# Jelly, ~~13~~ 7 bytes

**6 bytes thanks to Zgarb for his algorithm.**

```
~~BŒgµL*x@Ḣµ€FḄ~~
BŒgḄBFḄ

```

Try it online!
> 2 votes

# Answer
## C#, ~~112~~ 91 bytes

```
int x(int x)=>Convert.ToInt32(Regex.Replace(Convert.ToString(x,2),"0+","0"),2);

```

-8 bytes thanks to TuukkaX
> 2 votes

# Answer
## Perl, 38 + 1 (`-p`) = 39 bytes

```
$_=oct"0b".sprintf("%b",$_)=~s/0+/0/gr

```

Needs `-p` flag to run (I added `-l` flag to make it more readable, but it's not needed otherwise) :

```
perl -plE '$_=oct"0b".sprintf("%b",$_)=~s/0+/0/gr' <<< "1
9
15
13
16
17
65535
65000"

```

Note much to say about the code : it converts the number into binary (`sprintf"%b"`), then replaces blocs of zeros by just one zero, and converts the result into decimal (`oct"0b".`).
> 2 votes

# Answer
# Java, 75

```
int f(Integer x){return x.valueOf(x.toString(x,2).replaceAll("0+","0"),2);}

```

Test program:

```
public class Fit {
    int f(Integer x){return x.valueOf(x.toString(x,2).replaceAll("0+","0"),2);}

    public static void main(final String... args) {
        final Fit x = new Fit();
        System.out.println(x.f(65000));
    }
}

```
> 2 votes

# Answer
# PARI/GP, ~~54~~ 43 bytes

```
n->fold((a,b)->a+if(b,a+1,a%2,a),binary(n))

```
> 2 votes

# Answer
# C, 37 bytes

```
f(x){return x?f(x/2)<<!!(x%4)|x&1:0;}

```
> 2 votes

# Answer
# Reference Implementation in S.I.L.O.S "only" 417 bytes

Golfed

```
readIO :
i + 1
I = i
z = 1
n = 32
b = n
z = 1
n = b
lbla
n - 1
GOSUB p
j = i
j - p
if j b
if z c
z = 1
GOTO e
lblc
b - 1
if n a
GOTO f
lblb
z = 0
A = a
A + 1000
set A 1
i - p
lble
a + 1
if n a
lblf
q = 1000
e = q
e + b
i = 0
lbl>
d = q
d - e
if d ?
n = b
n - i
GOSUB p
g = get q
g * p
o + g
i + 1
q + 1
GOTO >
lbl?
o / 2
printInt o
GOTO z
funcp
p = 1
Z = n
lblQ
if Z C
GOTO D
lblC
Z - 1
p * 2
GOTO Q
lblD
return
lblz

```

Here is the reference implementation fully ungolfed. As a bonus feature it outputs the steps needed to come to an answer.

```
/**
*Reference Implementation in the high quality S.I.L.O.S language.
*/
readIO Enter a number to "compress"
//some declarations
i + 1
I = i
z = 1
//the above is a flag which shows whether or not a zero was last outputted
n = 32
b = n
//maximum number of input bits
printLine Original Binary

lblbinLoop
n - 1
GOSUB pow
j = I
j - p
if j printOne
if z ENDLOOP
print 0
GOTO ENDLOOP
lblprintOne
z = 0
print 1
I - p
lblENDLOOP
if n binLoop

printLine
printLine Binary "Compressed"

z = 1
n = b

lbltopA
n - 1
GOSUB pow
j = i
j - p
if j printAOne
if z DontPrint
z = 1
print 0
GOTO ENDLOOPA
lblDontPrint
b - 1
if n topA
GOTO endOfBin
lblprintAOne
z = 0
print 1
A = a
A + 1000
set A 1
i - p
lblENDLOOPA
a + 1
if n topA

lblendOfBin

printLine
printLine -----------
printLine Base 10 Output
print Out Bits:
printInt b

q = 1000
e = q
e + b
i = 0
lblOutputDec
d = q
d - e
if d DONE
n = b
n - i
GOSUB pow
g = get q
g * p
o + g
i + 1
q + 1
GOTO OutputDec
lblDONE
printLine
printLine ---------
o / 2
printInt o

GOTO funcs
//function declarations must be wrapped in gotoes to avoid the interpreter from complaining (breaking)

/**
*This will store the nth power of two in the "p" variable
*/
funcpow
p = 1
Z = n
lbltop
if Z continue
GOTO end
lblcontinue
Z - 1
p * 2
GOTO top
lblend
return

lblfuncs

```

By request the transpilation has been deleted. Feel free to view the edit history to recover it, otherwise go to this repo for an interpreter.

Sample output for 65000

```
Enter a number to "compress"
65000
Original Binary
1111110111101000
Binary "Compressed"
11111101111010
-----------
Base 10 Output
Out Bits:14
---------
16250

```
> 1 votes

# Answer
## PowerShell v2+, 69 bytes

```
[convert]::ToInt32(([convert]::ToString($args[0],2)-replace'0+',0),2)

```

(*A shorter way to convert to/from binary in PowerShell*)

Takes input `$args[0]`, uses the .NET built-in `[convert]::ToString(int,base)` to convert the input integer into a binary base string. That's filtered through the `-replace` to strip out any runs of one-or-more-zeros to just `0`. That resultant string is sent back through the other direction via `[convert]::ToInt32(string,base)` to turn the binary back into an integer. That integer is left on the pipeline and output is implicit.

### Test Cases

```
PS C:\Tools\Scripts\golfing> 1,9,15,13,16,17,65535,65000|%{"$_ -> " +(.\output-fit-number.ps1 $_)}
1 -> 1
9 -> 5
15 -> 15
13 -> 13
16 -> 2
17 -> 5
65535 -> 65535
65000 -> 16250

```
> 1 votes

# Answer
# Java, ~~152~~ ~~143~~ 138 bytes

```
interface C{static void main(String[]b){Integer i=0;System.out.print(i.parseInt(i.toString(i.parseInt(b[0]),2).replaceAll("0+","0"),2));}}

```
* 9 bytes less thanks to @RohanJhunjhunwala. I prefer to keep it as a fully functioning program with main and the like. However, of course it can be golfed more otherwise.
* 5 bytes less thanks to @LeakyNun's suggestions.
> 1 votes

# Answer
# Pyth, 12

```
i:.BQ"0+"\02

```

Online.

```
  .BQ            # Convert input from base 10 to base 2
 :   "0+"\0      # Replace multiple zeroes with single zero
i          2     # Convert back from base 2 to base 10

```
> 1 votes

# Answer
# Retina, 30 bytes

```
.+
$*1;
+`(1+)\1
$1;
1;
1
;+
0

```

Try it online!

And here I thought Retina would be amongst the first answers...
> 1 votes

# Answer
# Dyalog APL, 19 bytes

```
{2⊥⍵/⍨~0 0⍷⍵}2∘⊥⍣¯1

```

TryAPL online!

**This function is really an "atop" of two functions, the first function is:**

`2∘⊥⍣¯1` the *inverse* of binary-*to*-decimal conversion, i.e. binary-*from*-decimal conversion
*two* `2` *is bound*  to *-to-decimal*
*repeat* the operation  *negative one* time `¯1` (i.e. once, but inverted)

**In the second function, the above's binary result is represented by** **:**

`{2⊥⍵/⍨~0 0⍷⍵}`
`0 0⍷⍵` Boolean for where {0, 0} begins in ⍵
`~` Boolean negation, so now we have ᴛʀᴜᴇ everywhere but at non-first zeros in zero-runs
`⍵/⍨` use that to filter ⍵, so this removes our unwanted zeros
`2⊥` convert binary-to-decimal
> 1 votes

# Answer
# TSQL, 143 bytes

Not using build ins to convert from and to binary.

Golfed:

```
DECLARE @i INT=65000

,@ CHAR(99)=''WHILE @i>0SELECT @=REPLACE(LEFT(@i%2,1)+@,'00',0),@i/=2WHILE @>''SELECT @i+=LEFT(@,1)*POWER(2,LEN(@)-1),@=STUFF(@,1,1,'')PRINT @i

```

Ungolfed:

```
DECLARE @i INT=65000

,@ CHAR(99)=''
WHILE @i>0
  SELECT @=REPLACE(LEFT(@i%2,1)+@,'00',0),@i/=2

WHILE @>''
  SELECT @i+=LEFT(@,1)*POWER(2,LEN(@)-1),@=STUFF(@,1,1,'')

PRINT @i

```

**Fiddle**
> 1 votes

# Answer
# CJam, 16

```
q~2b1+0a%0a*);2b

```

Try it online

It's quite long due to lack of regex.

**Explanation:**

```
q~     read and evaluate the input number
2b     convert to base 2 (array of 1s and 0s)
1+     append a 1 to deal with trailing zeros
0a%    split by [0], dropping empty pieces; only chunks of 1s are left
0a*    join by [0]
);     discard the 1 we appended before
2b     convert back from base 2

```
> 1 votes

# Answer
# CJam, 23 bytes

```
ri2be`{_:g:>{:g}&}%e~2b

```

**Try it online!**

### Explanation

```
ri          e# Read input as an integer
2b          e# Convert to binary
e`          e# Run-length encoding. Gives a nested (2D) array with run-lengths
            e# and binary digits
{           e# This block is mapped over the outer array, i.e. is applied to
            e# each inner array
   _        e#   Duplicate the inner array
  :g        e#   Signum of each element of inner array
  :>        e#   This gives true if second element (digit) is false and first
            e#   element (run-length) is not zero. If so, we need to set that
            e#   run-length to 1
  {:g}&     e#   If that's the case, apply signum to original copy of inner
            e#   array, to make run-length 1
}%          e# End block which is mapped over the outer array
e~          e# Run-length decoding
2b          e# Convert from binary. Implicitly display

```
> 1 votes

# Answer
# Java, 64 bytes

```
i->{return i.parseInt(i.toString(i,2).replaceAll("0+","0"),2);};

```

# Test Program

```
public static void main(String[] args) {
    Function<Integer, Integer> function = i -> {
        return i.parseInt(i.toString(i, 2).replaceAll("0+", "0"), 2);
    };

    System.out.println(function.apply(1)); // 1
    System.out.println(function.apply(9)); // 5
    System.out.println(function.apply(15)); // 15
    System.out.println(function.apply(13)); // 13
    System.out.println(function.apply(16)); // 2
    System.out.println(function.apply(17)); // 5
    System.out.println(function.apply(65535)); // 65535
}

```
> 1 votes

# Answer
### Ruby, 37 35 bytes

Saved two bytes thanks to manatwork.

```
->a{a.to_s(2).gsub(/0+/,?0).to_i 2}

```

The naive approach. (:
> 1 votes

# Answer
# S.I.L.O.S, 120 bytes

```
readIO
p = 1
lbla
m = i
m % 2
M = m
M - 1
M * F
M + 2
p * M
F = 1
F - m
A = p
A * m
r + A
i / 2
if i a
r / 2
printInt r

```

Try it online!

This is basically a state machine.

* `p` for the current power
* `m` for the result of the modulo by 2
* `M` for the multiplier (to the power); if we are stuck at zeroes, the multiplier would be 1
* `F` for the flag, to denote whether the zero is the first zero in the run.
* `r` for the result, which is printed at the end.

The conversion between `m`, `M` and `F` is as follows:

* `m=0, F=0 -> F=1, M=2` (first zero, multiply by 2 anyway)
* `m=0, F=1 -> F=1, M=1` (not the first zero, multiply by 1)
* `m=1, F=0 -> F=0, M=2` (it is a one, multiply by 2, reset flag)
* `m=1, F=1 -> F=0, M=2` (it is a one, multiply by 2, reset flag)

Essentially we come up with the following formula:

* `M=((m-1)*F)+2`
* `F=1-m`
> 1 votes

# Answer
# Oasis, 25 bytes (non-competing)

```
n2÷an»»n»4÷xx-p>*nn2÷x-+0

```

Try it online!

I have not failed my master. \o/

There are many missing features which must be built. For example, there is no conditionals, so the formula I am using would be `f(n/2)*[1+(n%4>0)] + n%2`.

Actually, there is no modulo either, so `n%2` is implemented as `n-(n/2*2)` where `/` is integer division.

I did not mention `n%4`, because there is no `>` either. The `>` in the code means `+1`. So, `n%4>0` is built from `is_prime(((n+2)%4)+2)` where the modulo is generated as above.
> 1 votes

# Answer
# Husk, <sup>~~11 10~~</sup> 9 bytes

```
ḋṁS↑o→Σgḋ

```

Try it online!

-1 byte from H.PWiz.

-1 byte from Jo King.

# Alternative 9-byter

```
ḋṁ?uIΛ¬gḋ

```

Try it online!

## Explanation

```
ḋṁ?uIΛ≠1gḋ
         ḋ get binary digits
        g  group equal runs of digits
 ṁ         map each group to the following, and concatenate:
  ?  Λ≠1   if all elements are not equal to 1
   u       uniquify the group
    I      else leave it as is
ḋ          convert back to base-10

```
> 1 votes

# Answer
# J-uby, 29 bytes

Based on my Ruby answer.

```
:%&"0b%b"|~:squeeze&?0|-:eval

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, number, sequence
---


title: Create a nibble shorthand

text:
# Question
Title: Create a nibble shorthand
I recently stumbled across this image on wikimedia commons. It's a little bit of an information overload at first, but after examining it a bit it shows an interesting number system for writing nibbles.

*Image created by user Watchduck.*

First off a "nibble" is a 4 bit number which is really a number ranging from 0 to 15, with a particular emphasis on binary. This diagram shows a shorthand for writing such numbers with each number being one symbol. Ok, who cares? Plenty of people make up new symbols for numbers all the time. Well the interesting thing about these numbers is their symmetry.

If you take one of the symbols and mirror it horizontally you get the symbol of the number with the same bits in reverse order. For example the symbol that sort of looks like a 3 represents the bits 0011, it's horizontal mirror represents the bits 1100. Numbers which are symmetric along this mirror represent nibbles which are palindromes.

Similarly if you take a symbol and rotate it a half turn (180 degrees) you get the symbol for the bitwise compliment of that number, for example if you take the symbol that looks like a 7, it represents 0111, if you rotate it a half turn you get a symbol representing 1000.

## Task

You will write a program or function which takes as input a nibble and outputs an image of a symbol. Your symbols are not required to be anything in specific but they are required to have the symmetry properties.

1. Distinct nibbles should give distinct symbols
2. The symbol for a nibble \\$r\\$ should be the mirror image of the symbol for the reverse of \\$r\\$.
3. The symbol for a nibble \\$r\\$ should be the symbol for the bitwise compliment of \\$r\\$ rotated 180 degrees.

You may take input in any reasonable format and output in any image or graphical format. There are no additional requirements on resolution, aside from those implied by the rules. You can make your symbols as small as you wish as long as you satisfy the rules.

This is the goal is to minimize the size of your source code as measured in bytes.

# Answer
> 18 votes
# MATL, ~~12~~ 7 bytes

```
t~Pv1YG

```

Input is a 4-digit binary vector.

**Example outputs** (or try it at **MATL Online**!):

* Input `[0 1 0 0]`:

* Input `[1 0 1 1]`:

* Input `[1 1 0 1]`:

* Input `[1 0 0 1]`:

* Input `[0 1 1 0]`:

### How it works

The output is a 2-row, 4-column image where the first row corresponds to the input binary digits, and the second row is the first element-wise negated and reversed.

```
t     % Implicit input. Duplicate
      % STACK: [0 1 0 0], [0 1 0 0]
~     % Negate, element-wise
      % STACK: [0 1 0 0], [1 0 1 1]
P     % Reverse
      % STACK: [0 1 0 0], [1 1 0 1]
v     % Vertically concatenate
      % STACK: [0 1 0 0; 1 1 0 1]
1YG   % Display image with scaled colors. 0 is shown as black, 1 as white

```

# Answer
> 7 votes
# Ruby, 106 bytes

Takes an integer as input and returns a PBM image.

```
->i{t="'/%[g|eS
smR\rzrt"
"P1
5 3
"+("%08b"%t[t.index(i.chr)+1].ord).gsub(/./,'\&0')[1..]}

```

Attempt This Online!

The code has unprintable characters that make it copy-and-paste-unfriendly; expand the below snippet for an xxd dump if you want to try it on your own machine.

```
00000000: 2d3e 697b 743d 2200 1701 2702 2f03 2504  ->i{t="...'./.%.
00000010: 5b05 6706 7c07 6508 5309 1f0a 730b 6d0c  [.g.|.e.S...s.m.
00000020: 525c 727a 0e72 0f74 220a 2250 310a 3520  R\rz.r.t"."P1.5
00000030: 330a 222b 2822 2530 3862 2225 745b 742e  3."+("%08b"%t[t.
00000040: 696e 6465 7828 692e 6368 7229 2b31 5d2e  index(i.chr)+1].
00000050: 6f72 6429 2e67 7375 6228 2f2e 2f2c 2726  ord).gsub(/./,'&
00000060: 3027 295b 312e 2e5d 7d0a                 0')[1..]}.
```

## The shorthand

## How it works

The images are 5×3 but there are only 7 "real" pixels, in a hex pattern:

```
 1 1
1 1 1
 1 1

```

This makes each image's data fit in a byte. `t` is a lookup table where the ASCII character corresponding to each nibble is followed by the character corresponding to its image representation. The code looks up the image data in the table, formats it as a string of `1`s and `0`s, interleaves the extra `0`s, and returns it in PBM format.

## Ungolfed

```
->input{
  table = "\x00\x17\x01\x27\x02\x2f\x03\x25\x04\x5b\x05\x67\x06\x7c\x07\x65\x08\x53\x09\x1f\x0a\x73\x0b\x6d\x0c\x52\x0d\x7a\x0e\x72\x0f\x74"
  image_byte = table[table.index(input.chr) + 1].ord
  image_data = ("%08b" % image_byte).gsub(/./,'\&0')[1..]

  "P1
5 3
" + image_data
}

```

# Answer
> 6 votes
# Python 3 \+ NumPy and Pillow, ~~101~~ ~~92~~ ~~91~~ ~~82~~ 77 bytes

```
import numpy as n,PIL.Image as p
lambda x:p.fromarray(n.array([x,1-x[::-1]]))

```

Takes in a NumPy array of ones and zeros and returns the resulting 4x2 image. Basically a copy of Luis Mendo's answer in Python. Ungolfed:

```
import numpy as np
from PIL import Image

def represent(nibble: np.array) -> None:
    representation = np.array([nibble, 1 - nibble[::-1])
    image = Image.fromarray(representation)
    return image

```

Thanks to Louis Mendo, who figured this out (and then saved me 9 bytes)!

Examples:

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

* `[1, 1, 1, 1]`

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

I have no idea where the blurring comes from. However, it still satisfies the criteria. Note that in these images, the colors are RGB (0, 0, 0) and (255, 255, 255), for human readability. However, in the image generated by the program, the colors are (0, 0, 0) and (1, 1, 1), which, while distinct, cannot be told appart using a human eye.

* -9 thanks to Luis Mendo
* -1 thanks to Jonathan Allen
* -9 because I figured out I could return the image instead of displaying it, and not assign this to a variable
* -5 again thanks to Jonathan Allen

# Answer
> 6 votes
## JavaScript (browser), ~~187~~ 182 bytes

```
f=
(n,c)=>c.getContext`2d`.putImageData(new ImageData(new Uint8ClampedArray(Int32Array.from([...s=n.toString(2).padStart(4,0),...[...s].reverse()],(c,i)=>-1<<(c^i/4)*24).buffer),4),0,0)
```

```
canvas{width:256px;height:128px;image-rendering:pixelated;}
```

```
<input type=number size=2 min=0 max=15 oninput=f(+this.value,c)><div><canvas id=c height=2 width=4>
```

Uses @LuisMendo's method. Draws the output on a `2×4` canvas passed as the second parameter, but the snippet scales the output up 64 times for convenience.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 23 bytes

A port of @Luis Mendo's MATL answer.

```
Image@{#,Reverse[1-#]}&

```

# Answer
> 3 votes
# Jelly, 12 bytes

```
142D;Ṛ;¬K”P;

```

A full program that outputs a PBM file on STD OUT.

**Try it online!**

### How?

Jelly cannot produce images on screen, so this places an image file content on STD OUT ready to be directed to a file.

The PBM format idea came from Jordan's Goruby and Ruby posts. Go upvote!

The method is similar to Luis Meno's MATL post, because there is nothing simpler. Go upvote!

The only difference is that rather than the number on top of the reversed negated number we have the reverse of the number on top of the negated number.

```
142D;Ṛ;¬K”P; - Main Link: list of four bits, N     e.g. [0,0,1,0]
142          - 142
   D         - to decimal digits -> [1, 4, 2]
     Ṛ       - reverse (N)                              [0,1,0,0]
    ;        - concatenate                              [1,4,2,0,1,0,0]
       ¬     - logical NOT (N)                          [1,1,0,1]
      ;      - concatenate                              [1,4,2,0,1,0,0,1,1,0,1]
        K    - join with spaces                         [1,' ',4,' ',2,' ',0,' ',1,' ',0,' ',0,' ',1,' ',1,' ',0,' ',1]
         ”P  - 'P'
           ; - concatenate                              ['P',1,' ',4,' ',2,' ',0,' ',1,' ',0,' ',0,' ',1,' ',1,' ',0,' ',1]
             - implicit, smashing print                 P1 4 2 0 1 0 0 1 1 0 1
                                                        i.e. the pixels:
                                                        0100
                                                        1101

```

# Answer
> 3 votes
## HTML + Javascript 70 + ~~159~~ ~~154~~ 151 = 221 bytes

The output is topologically like Jordan's, with the output rotated by 90° and lines instead of dots. This achieves a classical seven part display. The symbols also loosely resemble those used by Watchduck in his original grafic in shape and order.

The order of the elements is

```
  0            M1,1h3
1   2      M1,1v3  M4,1v3
  3             M1,4h3
4   5      M1,4v3  M4,4v3
  6            M1,7h3

```

After experimenting with multiple other variants, I find it interesting that this intuitive ordering still gives the shortest path production.

The Bigint holds the shown elements for each symbol as bits ordered right to left. Since the symbol for 1111, the last symbol, has no shown elements in the lower half, the last (leftmost) hex digit is 0, and the number can be written in hex with 27 digits instead of the expected 16\*7/4 = 28.

*-5 bytes thanks to Steffan.*

*-3 bytes for bitwise operation on `BigInt` and symbol reordering.*

```
f=n=>{for(d='',i=0;i<7;i++)0xe5cfdb4f4dbf24fdb2f2dbf3a70n>>BigInt(n*7+i)&1n?d+=`M${(i+1)%3?1:4},${(i/3&3)*3+1}${i%3?'v':'h'}3`:0;p.setAttribute('d',d)}
```

```
<input oninput=f(value)><svg viewBox=0,0,5,8><path id=p stroke=#000 />
```

### Ungolfed and a bit more pretty

```
f = n => {
    t = 0xe5cfdb4f4dbf24fdb2f2dbf3a70n
    for (d='',i=0; i<7; i++) {
        if (t>>BigInt(n*7+i)&1n) {
            d += `M${(i+1)%3?1:4},${(i/3&3)*3+1}${i%3?'v':'h'}3`
        }
    }
    p.setAttribute('d', d)
}
f(0)
```

```
<input type=number size=2 value=0 min=0 max=15 oninput=f(value)>
<div>
  <svg viewBox=0,0,5,8 width=80>
    <path id=p stroke=#000 />
  </svg>
</div>
```

# Answer
> 2 votes
# Goruby, 37 bytes

Takes an array of `0`s and `1`s and returns a PBM image.

Same technique as Luis Mendo's answer.

```
->a{"P1
4 2
#{a+a.rv.m{_1>0?0:1}}"}

```

Attempt This Online!

# Answer
> 2 votes
# Desmos, 44 bytes

```
L=[0...3]
f(l)=join((L[l>0],1),(3-L[l=0],0))

```

I have no idea what this question is asking about; I'm just porting most of the other answers here.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# Fig, \\$16\log\_{256}(96)\approx\\$ 13.17 bytes

```
J/Pj/ JJf142$xe!

```

Try it online!

Outputs as a PBM image. Port of Jelly, so go upvote that (and the posts that inspired it)!

# Answer
> 1 votes
# K (ngn/k), ~~35~~ 33 bytes

```
{`0:"P1\n4 2\n",*',/$x,"\n",$|~x}

```

Try it online!

Took me quite some time, but I finally got it. Output PBM image data, as that seems to be what everyone's doing.

Forgive me if the explanation doesn't make sense. Neither do I understand it well.

Explanation:

```
{`0:"P1\n4 2\n",*',/$x,"\n",$|~x}    Main program. Takes x as input
                               x     x itself
                             |~      Not, then reverse
                            $        Convert each number to string
                       "\n",         Concat with newline
                      ,              Concat with
                    $x               x, with each number converted to string
                  ,/                 Joined everything together
                *'                   Get the first element of each string.
                                     This is to remove the sub-arrays of the negate-then-reverse x
               ,                     Concat the entire result with
    "P1\n4 2\n"                      PBM hardcoded image data. Defined an image of 2x4 pixels
 `0:                                 Print everything to stdout

```

---
Tags: code-golf, graphical-output, binary, open-ended-function
---