title: Construct a Modulo Multiplication Table

text:
# Question
Title: Construct a Modulo Multiplication Table
Consider a `n x n` multiplication table and replace each item with its remainder of division by `n`. For example, here is a `6x6` table and its "modulo 6" structure: (The last column and row are ignored since both are null)

```
1  2  3  4  5  6   |   1 2 3 4 5
2  4  6  8 10 12   |   2 4 0 2 4
3  6  9 12 15 18   |   3 0 3 0 3
4  8 12 16 20 24   |   4 2 0 4 2
5 10 15 20 25 30   |   5 4 3 2 1
6 12 18 24 30 36   |

```

Now it is evident that the multiplication table modulo n is symmetric and can be reconstructed by one of its triangular quadrants:

```
1 2 3 4 5
  4 0 2
    3

```

## Challenge

Given a positive integer N, print the upper quadrant of multiplication table modulo N. Assume that there is no restriction on the width of string in your output environment. The alignment of numbers shall be preserved. This means, the output should look like a part of a **uniform** product table, where the cells have equal widths. So for example, if we have a two-digit number in the table, all single-digit entries are separated by two spaces.

## Rules

Standard rules apply.

## Test cases

```
N = 1:
// no output is printed

N = 3:
1 2

N = 13:
1  2  3  4  5  6  7  8  9 10 11 12
   4  6  8 10 12  1  3  5  7  9
      9 12  2  5  8 11  1  4
         3  7 11  2  6 10
           12  4  9  1
              10  3

```

Sandbox

# Answer
> 2 votes
# Charcoal, 32 bytes

```
Ｅ⊘θ⪫Ｅ⊖θ◧⎇‹›ιλ‹⁺ιλ⊖θＩ﹪×⊕ι⊕λＩθωＬθ

```

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

```
  θ                                 Input `n`
 ⊘                                  Halved
Ｅ                                   Map over implicit range
      θ                             Input `n`
     ⊖                              Decremented
    Ｅ                               Map over implicit range
        ⎇‹›ιλ‹⁺ιλ⊖θ                 If this entry is wanted
                      ⊕ι            Row value
                     ×              Multiplied by
                        ⊕λ          Column value
                    ﹪               Modulo
                          Ｉθ        `n` as an intger
                   Ｉ                Cast to string
                            ω       Otherwise the empty string
       ◧                     Ｌθ     Pad to length of `n`
   ⪫                                Join with spaces
                                    Implicitly print

```

# Answer
> 9 votes
# Jelly, 14 bytes

```
’×þ%ɓoU¥⁺GµḶ⁶ẋ

```

Try it online!

Outputs a bunch of trailing whitespace. Used the `’×þ%` trick from hyper-neutrino's answer, so be sure to give them an upvote

## How it works

```
’×þ%ɓoU¥⁺GµḶ⁶ẋ - Main link. Takes N on the left
’              - Decrement
 ×þ            - Create a multiplication table for all integers from 1 to N-1 and 1 to N
   %           - Mod each by N. This leaves a trailing row of zeros.
                 Call this table T

           Ḷ   - Yield [0, 1, 2, ..., N-1]
            ⁶ẋ - Yield that many spaces for each
                 Call this list of spaces S

    ɓ     µ    - New dyadic chain f(S, T):
       ¥       -   Group the previous 2 links into a dyad g(S, T):
     o         -     For each row in S and T, replace the first N elements of the row in T with spaces,
                      where N is the number of spaces in the row in S
      U        -     Reverse each row
        ⁺      -   Do it again
         G     -  Format it as a grid and output

```

# Answer
> 5 votes
# Jelly, 14 bytes

```
’×þ%µJ’⁶ẋoUµ⁺G

```

Try it online!

I stole the idea to use logical OR to avoid needing to trim and re-pad the lists from caird. Go upvote their solution too, please.

```
’×þ%µJ’⁶ẋoUµ⁺G   Main Link; accepts x
’                x - 1
 ×               using multiplication
  þ              create a product table (this does x - 1 by x)
   %             modulo x
----µ---------   start a new chain on this table
     J           range over length (1, 2, ..., N)
      ’          decrement (0, 1, 2, ..., N - 1)
       ⁶ẋ        repeat " " by ^
         o       vectorized logical OR; basically fills the lower left triangle with spaces
          U      reverse each row
     ------µ⁺    duplicate the last chain, so this fills the lower left and flips horizontally twice, thus cutting the list to just the upper triangle
             G   format as grid

```

# Answer
> 5 votes
# , 60 55 bytes

```
1}."1,/"2@((' ',.' ',":@,.){~(<|.)@(>/~)*1+#|>:*/>:)@i.

```

Try it online!

-5 thanks to xash

I thought this would be a good challenge for J, and the essence of the problem is, but the formatting details destroyed me here.

# Answer
> 5 votes
# \>= 4.1.0, ~~165~~ 152 bytes

```
\(n,`/`=sprintf){z=outer(1:n,1:n,\(x,y)(x*y)%%n[2-(pmin(y,n-y)>=x)]);z[is.na(z)]="";z[]="%%%ds"/nchar(n-1)/z;cat(apply(z,1,paste,collapse=" "),sep="
")}

```

Try it online!

An anonymous function that takes an integer and prints the triangle to STDOUT. The TIO link replaces `\` with `function` since TIO is on an earlier version of R.

Thanks to @RobinRyder for saving 5 bytes, and @KirillL for saving a further 8!

# Answer
> 4 votes
# MATLAB/Octave, 117 bytes

```
function f(n)
r=1:n;m=num2str(mod(r'*r,n));s=(nnz(m(1,:))+2)/n;for k=1:n
m(k,1:k*s-s)=32;disp(m(k,1:(n-k)*s))
end
end

```

Try it online! This prints out quite a lot of trailing whitespaces. If we sacrifice 2 bytes to replace `k=1:n` with `k=1:n/2` the empty lines won't be printed though.

Despite my efforts to find more elegant solution using `triu` function (takes upper triangle of square matrix) this stayed the shortest solution I came up with.

Ungolfed/explained:

```
function f(n)
r=1:n;
m=num2str(mod(r'*r,n)); % modulo table transformed to char array
s=(length(m(1,:))+2)/n; % how many characters takes up one number
for k=1:n
  m(k,1:k*s-s)=' ';     % replace first k-1 numbers with spaces
  disp(m(k,1:(n-k)*s))  % print first n-k numbers
end
end

```

# Answer
> 3 votes
# JavaScript (ES8), 92 bytes

Expects the input as a string.

```
n=>(g=k=>++k>n/2?'':(h=i=>++i>n-k?`
`:(i<k?'':i*k%n+'').padStart(n.length+1)+h(i))``+g(k))``

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~113~~ 96 bytes

```
def f(n):d=range(1,n);[print(*[f"{['',v*x%n][v>=x<=n-v]:{len(str(n-1))}}"for v in d])for x in d]

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~43~~ ~~41~~ 35 bytes (SBCS)

Anonymous prefix lambda.

```
{1↓⍕d⍪' '@{∨∘⌽⍨∘.>⍨⍳d}⍵|∘.×⍨⍳d←⍵-1}

```

Try it online!

`{``}` "dfn"; N is :

`d←⍵-1` let `d` be N minus one

indices one through N

`∘.×⍨` multiplication table

`⍵|` that modulus N

`' '@{``}` replace with spaces **at** locations indicated by:

`⍳d` indices one through `d`

`∘.>⍨` greater-than table

`∨∘⌽⍨` logical OR with its own mirror image

`d⍪` prepend a row of `d`s (to size columns widths right)

format to character matrix

`1↓` drop the first row

# Answer
> 2 votes
# Jelly, ~~16~~ 15 bytes

```
’<þa⁶oU$o’×þ%ƊG

```

Try it online!

Also outputs a ton of trailing whitespace

# Answer
> 2 votes
# , 109 bytes

```
n=scan();m=(1:n%o%1:n%%n)[,-n];m[l<-lower.tri(m)]="";m[l[,n-1:n]]="";write.table(format(m,j="r"),,,F,r=F,c=F)

```

Try it online!

A full program with some hacking around the built-in formatting/printing functionality to achieve the desired result. Here is the printing statement with all the formatting options ungolfed:

```
write.table(format(m,justify="right"),quote=FALSE,row.names=FALSE,col.names=FALSE)

```

If printing the numbers left-aligned is allowed after all, then we can save a few extra bytes by removing right-justification.

# Answer
> 1 votes
# Stax, 16 bytes

```
ù▼åU☻┐≈◘E╝ÖBñGRR

```

Run and debug it

about as short as I could get it. centering the stuff took more bytes than i expected.

## Explanation

```
vc{*x%K{itiT|>Jm|Cm
vc                  decrement and duplicate input n
  {   K             cross-product map ranges (1..n-1) and (1..n-1)
   *                multiply the numbers
    x%              mod n
       {       m    map each row to
        itiT        iteration number trimmed from both sides
            |>      right align each number
              J     join with spaces
                |C  center
                  m print joined with newlines

```

# Answer
> 1 votes
# Vyxal `CM`, ~~35~~ 30 bytes

```
ƛ⁰ɽƛ⁰ɽ*⁰%;$in(ṪḢ);ƛƛ:L⁰Lεð*p;Ṅ

```

Try it Online!

```
ƛ⁰ɽƛ⁰ɽ*⁰%;$in(ṪḢ);ƛƛ:L⁰Lεð*p;Ṅ
ƛ                ;                For each n in range(0,input):
 ⁰ɽƛ     ;                         Generate the table: For each in range(1,input):
    ⁰ɽ*                            Multiply by range(1,input) to make a table.
       ⁰%                          Mod(input) everything
          $i                       Make a triangle: Get the nth row of the table
            n(  )                  Repeat n times:
              ṪḢ                    Remove the head and tail

                                  Align the numbers:
ƛ                                 For each row of the triangular table:
 ƛ        ;                        For each number in that row:
  :L⁰Lε                             Take difference of length(input) and length(number)
       ð*p                          Prepend that many spaces
           Ṅ                       Join each row on spaces

```

`C` centers the output, and `M` makes implicit ranges start from 0.

Improvements welcome.

# Answer
> 1 votes
# C (gcc) `-lm`, 96 bytes

-7 thanks to @ceilingcat

```
w,i,j;f(a){w=log10(a)+2;for(i=0;i++<a;puts(""))for(j=i;j+i<=a;)printf("%*d",j++-i?w:w*i,i*j%a);}

```

Try it online!

---

# C (gcc), ~~106~~ 103 bytes

-3 thanks to @ceilingcat

```
w,i,j;f(a){for(w=2,i=a;i/=10;w++);for(;i++<a;puts(""))for(j=i;j+i<=a;)printf("%*d",j++-i?w:w*i,i*j%a);}

```

Try it online!

# Answer
> 1 votes
# 05AB1E (legacy), 26 bytes

Without trailing/leading spaces/newlines (**26 bytes**):

```
L¨Dδ*s%εNF¦¨]DZg>jðδÛ˜õK.c?

```

Try it online or verify all test cases.

With leading spaces and trailing spaces/newlines (**20 bytes**):

```
L¨Dδ*s%εNF¦¨]DZg>j.c

```

Try it online or verify all test cases.

**Explanation (of the longer version):**

```
L               # Push a list in the range [1, (implicit) input]
 ¨              # Remove the final value to make the range [1, input)
                # Create a multiplication table matrix:
  D             #  Duplicate this list
   δ            #  Apply double-vectorized:
    *           #   Multiply
     s          # Swap so the (implicit) input is at the top of the stack
      %         # Modulo each value in the matrix by this
ε               # Map over each row:
 NF             #  Loop the (0-based) map-index amount of times:
   ¦¨           #   And remove the leading/trailing items
]D              # After both the inner loop and map: duplicate it
  Z             # Get the flattened maximum of this matrix (without popping)
   g            # Pop and get its length
    >           # Increase this length by 1
     j          # Prepend spaces in front of each integer up to that length+1,
                # and then join every row together to a single string
       δ        # Map over each inner string:
      ð Û       #  Strip leading spaces
         ˜      # Flatten this list (`δ` unfortunately wraps the strings in lists in the
                # legacy version..)
          õK    # Remove all trailing empty strings
            .c  # Centralize this list of strings
              ? # And output it without trailing newline

```

---
Tags: code-golf, matrix
---


title: Leave the times out!

text:
# Question
Title: Leave the times out!
Everyone knows, that you can leave out the multiplication symbol (\\$\times\\$, or `*`) in

* `a*b`
* `23*a`
* `(2+3)*a`
* `a^(b*c)`
* `(a+b)*(c+d)`

but not in

* `2*3` =\> you don't want it to be 23
* `a*23` =\> most mathematicians just don't do it
* `a^2*b` =\> now it's `(a^2)*b`, if you remove the `*`, it's `a^(2b)`
* `a/2*b` =\> now it's `(a/2)*b`, if you remove the `*`, it's `a/(2b)`
* `a*(2+3)` =\> most mathematicians just don't do it

But does a program know it to?

# Notes

* The input is an equation which has the basic operations (`+`, `-`, `*`, `/`, `^`), parentheses (`(`, `)`) and sometimes some 1-letter variables
* The output should be the input with unnecessary `*`s removed where possible

# Examples

```
a*b
> ab

2+3*a
> 2+3a

23+67/(56+7)
> 23+67/(56+7)

2t
> 2t

2*3+5/6*b
> 2*3+5/6*b

2*a*3
> 2a*3

2*-3
> 2*-3

a*-3
> a*-3

a^2*b
> a^2*b

a/2*b
> a/2*b

a*(2+5)
> a*(2+5)

(2+5)*a
> (2+5)a

23+(2*a)^(45*b)-c/5+24d+(2a)*(2b)
> 23+(2a)^(45b)-c/5+24d+(2a)(2b)

(a-b)*(2+e)
> (a-b)(2+e)

a*b*c
> abc

2*(3)
> 2(3)

(2)*(3)
> (2)(3)

2(3)
> 2(3)

(2)*3
> (2)3

```

# Answer
> 9 votes
# Wolfram Language (Mathematica), 5 bytes

```
Defer

```

`Defer` displays the expression in unevaluated form, leaving out the asterisks.

If you don't mind that Mathematica automatically combines some terms, and just want to eliminate the asterisks, no function is needed, giving the following 0-byte solution:

When it strips out the asterisks, `Defer` will usually remove mathematically unnecessary parentheses; however, they are sometimes retained for clarity:

When Defer removes a mathematically necessary asterisk, it will replace it with either parentheses or a `×` glyph:

For an additional 14 bytes (19 bytes total), Mathematica will dispense with both the asterisks and the times glyphs, using spaces instead.

To accomplish this, we need to operate `OutputForm` on `HoldForm`. Here `HoldForm` is needed instead of `Defer`, because while `Defer` *displays* the unevaluated form, it does not actually return the unevaluated form. To produce the desired result, `OutputForm` needs to operate on the unevaluated expression:

```
OutputForm@HoldForm

```

# Answer
> 5 votes
# Perl 5 (`-p`), 41 bytes

```
s;([/^]\d+\*)|\*(?=[a-z]|(?<=\).)\();$1;g

```

A regex substitution which validates all the test cases.

Try it online!

# Perl 5 (`-p`), 79 bytes

```
$_=reverse;s;([a-z]|\((?=.\)))\K\*(?!(\)([^()]|(?2))*\(|\w+)[/^]);;g;$_=reverse

```

Handling tsh's case Try it online!

# Answer
> 4 votes
# Python 3, ~~77~~ 76 bytes

Regex solution :

```
lambda x:re.sub("(?<![\^/].)\*(?=[A-z])","",x).replace(")*(",")(")
import re

```

Try it online!

Regex are ugly. Useful but ugly

Thanks to @ovs for -1 byte

# Answer
> 2 votes
# Python 3, 214 bytes

```
def f(x):
 s=''
 for i,c in enumerate(x):
  if(c=='*'):
   if ((x[i-1:i+2]==")*(")or(x[i-1].isalpha() and x[i+1].isalpha())or( x[i+1].isalpha())and(x[i-2]not in"^/"and x[i+1]not in"-+") ):
    c=''
  s+=c
 return s

```

Try it online!

ok this is really bad lol, sorry I'm new, any suggestion would be awesome!

EDIT: Ok, I think that's the shortest I can do lol, and FINALLY it works!

thanks to Kateba and Jakque for tips and ideas EDIT2: not doing lambda because I don't fully understand how it works lol

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


title: Crack the Lost Numbers

text:
# Question
Title: Crack the Lost Numbers
The Lost Numbers are 4, 8, 15, 16, 23, 42. Your goal is to create an expression to output them all.

Your allowed characters are 0123456789, ^+-\*/, (), % for modulo and n as the single variable allowed. Modified PEMDAS `()^*/%+-` is the precedence and / is normal division (3/2 = 1.5). 0^0 = 1 although division by 0 is undefined.

Create the shortest expression (in characters) such that for n = 0..5 (or 1..6 for 1-indexing) the nth Lost Number will be the result of the expression. Shortest expression wins.

# Answer
# 15 bytes

```
n*4+703%n^3%7*3

```

Try it online!

Based off @Arnauld's answer.

The idea was to look for a magic formula `A%n^B%C` that maps (1, 2, 3, 4, 5, 6) to (0, 0, 1, 0, 1, 6) to combine the last two terms in Arnauld's formula into one:

```
 n           |  1 |  2 |  3 |  4 |  5 |  6 | (x4)
 703%n^3%7   |  0 |  0 |  1 |  0 |  1 |  6 | (x3)
-------------+----+----+----+----+----+----+------
             |  4 |  8 | 15 | 16 | 23 | 42 |

```
> 8 votes

# Answer
# 20 characters

Assuming that the precedence of the operators is similar to JS. The input is expected to be 1-indexed.

```
n*4+16%n*3+6*0^(6-n)

```

Try it online! (interpreted in JS ES7)

### Breakdown

```
 n           |  1 |  2 |  3 |  4 |  5 |  6 | (x4)
 16 % n      |  0 |  0 |  1 |  0 |  1 |  4 | (x3)
 0 ^ (6 - n) |  0 |  0 |  0 |  0 |  0 |  1 | (x6)
-------------+----+----+----+----+----+----+------
             |  4 |  8 | 15 | 16 | 23 | 42 |

```
> 9 votes

# Answer
# ~~16~~ 15 characters

`6704196%(n*8+3)`

One-indexed. A simple application of a generalisation of the Chinese Remainder Theorem, with the formula n\*8+3 chosen to make it work (that is, where moduli have a common factor, the corresponding values' difference is also divisible by that factor), as well as to get a shorter number on the left.

Previously: `485559068%(n+41)`, zero-indexed
> 9 votes

---
Tags: arithmetic, atomic-code-golf
---


title: Another amicable number problem

text:
# Question
Title: Another amicable number problem
Two numbers are said to be 'amicable' or 'friends' if the sum of the proper divisors of the first is equal to the second, and viceversa. For example, the proper divisors of 220 are: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110 which sum up to 284. 284's proper divisors are 1, 2, 4, 71 and 142, which sum to 220, thus 220 and 284 are friends. Write a function which returns true if and only if a number is a friend of some other number.

Examples:

friend(220) ==\> true

friend(7) ==\> false

friend(284) ==\> true

Function with least number of chars wins.

**NOTE**: I just found out that there is a similar question, but I believe this one is simpler and perhaps more general.

# Answer
> 4 votes
## Python, 67

```
a=lambda x:sum(i for i in range(1,x)if x%i<1)
b=lambda x:x==a(a(x))

```

# Answer
> 4 votes
## Haskell, 47

```
o m=sum[x|x<-[1..m-1],m`mod`x<1]
f m=(o.o)m==m

```

Call the `f` function (for "friend").
Didn't provide a `main` because nobody else is doing so.

# Answer
> 2 votes
eTeX, 177 (yes, that language is too verbose)

```
\let~\ifnum\let\c\newcount\c\X\c\D\c\R\def\!{\advance\D1 ~\D<\X~\X=\numexpr\D*\numexpr
\X/\D\advance\R\D\fi\!\fi}\def\a#1{\X#1 \!\X\R\D0\R0 \!\message{~#1=\R YES\else NO\fi}\end}

```

Used as `etex filename.tex "\a{220}"`.

# Answer
> 2 votes
## APL (23)

Let me halve my score after 3 years of golfing. :)

This needs the function trains added to Dyalog APL 14, so it doesn't work on earlier versions, which at the moment of writing unfortunately includes the free (unregistered) version. It *does* work on TryAPL.

```
f←{+/∆×0=⍵|⍨∆←⍳⍵-1}⍣2=+

```

Or:

```
({+/∆×0=⍵|⍨∆←⍳⍵-1}⍣2=+)

```

(Because it involves a function train, it needs to be either parenthesized or named in order to use it. They both have the same character count, but the first needs to be entered and then called as `f 220`, the second needs to have its argument added to the right of it.)

Explanation:

* `{`...`}⍣2=+`: compare the argument to the result of running the function twice on the argument, return 1 if true and 0 if false
    + `∆←⍳⍵-1`: get all the numbers from 1 to ⍵-1 and store them in ∆.
    + `0=⍵|⍨∆`: get a binary vector which is 1 where `⍵ mod ∆` is 0 and 0 elsewhere
    + `+/∆×`: multiply ∆ by it and return the sum

# Answer
> 2 votes
# Brachylog, 11 bytes

```
fk+Xfk+?;X≠

```

Try it online!

Takes input through the input variable and outputs through success or failure.

```
fk+            The proper divisor sum of
               the input
   X           is X,
    fk+        and its proper divisor sum
       ?       is the input,
        ;X≠    which is not equal to X.

```

# Answer
> 2 votes
# Jelly, 4 bytes

```
Æṣ⁺=

```

Try it online!

My first Jelly answer! Doesn't really make use of any of the quirks of Jelly as a tacit language, but I'm still learning it.

Explanation:

```
Æṣ    # Sum of proper divisors of input
  ⁺   # Duplicate last link: Æṣ
   =  # Result of previous link = Input?

```

# Answer
> 1 votes
## Scala, 67

```
def d(n:Int)=(1 to n-1).filter(n%_==0).sum
def f(n:Int)=d(d(n))==n

```

# Answer
> 1 votes
**Ruby, 95**

```
l=lambda{|n|(1..n-1).select{|e|n.modulo(e)==0}.reduce(:+)}
m=lambda{|n|(l.call(l.call(n))==n)}

```

# Answer
> 1 votes
## Ruby 1.9, 57 characters

```
s=->n{eval (1...n).select{|a|n%a<1}*?+}
f=->n{s[s[n]]==n}

```

Pretty similar to all the other solutions here.

# Answer
> 1 votes
# J, 24 characters

The pure answer is this:

```
=(+/&(((0:=|~)#])i.))^:2

```

It's a monad that takes a scalar and returns 0 or 1 if it's a friend or not. Unfortunately J precedence rules make it impossible to use with no separator from its argument. I'm keeping the character count as such because of the way the question is worded. Anyway, here's a demonstration of three possible ways to use it:

```
   NB. using a named verb
   f =: =(+/&(((0:=|~)#])i.))^:2
   f 220
1
   NB. using parentheses
   (=(+/&(((0:=|~)#])i.))^:2) 7
0
   NB. using verb "Same"
   =(+/&(((0:=|~)#])i.))^:2 [ 284
1

```

Obligatory J unscrambling:

* `i. 220` returns the list of naturals below 220 (0, 1, 2 to 219)
* `(|~i.) 220` divides them all by 220 and returns the remainder
* `((0:=|~)i.) 220` compares to 0 (returns boolean as 0 or 1)
* `(((0:=|~)#])i.) 220` returns the natural where the 1s were. In effect: returns the full divisor list.
* `(+/&(((0:=|~)#])i.)) 220` sums them.
* `((+/&(((0:=|~)#])i.))^:2) 220` performs the operation twice.
* `(=(+/&(((0:=|~)#])i.))^:2) 220` checks we fall back on the initial argument.

# Answer
> 1 votes
# Vyxal, 5 bytes

```
∆K∆K=

```

Try it Online!

Pretty much identical to my Jelly answer.

Explanation:

```
       # Implicit input
∆K     # Sum of proper divisors
  ∆K   # Sum of proper divisors
    =  # Equal to input?

```

# Answer
> 0 votes
# Q, 42 33

```
{x={0+/a(&)0=x mod a:(!)6h$(1+x%2)}/[2;x]}

```

shorter by not limiting the check for divisors to enumerations up to n/2 but obviously slower as a result:

```
{x={0+/a(&)0=x mod a:(!)x}/[2;x]}

```

timing

```
q)\t {x={0+/a(&)0=x mod a:(!)x}/[2;x]} 2200000
289
q)\t {x={0+/a(&)0=x mod a:(!)6h$(1+x%2)}/[2;x]} 2200000
124

```

# Answer
> 0 votes
# JavaScript (E6) 57

```
F=n=>(S=n=>{for(t=d=1;++d<n;)n%d||(t+=d)},S(n),S(t),t==n)

```

# Answer
> 0 votes
# Pyth, 22 characters

```
DAdRsf!%dTr1dDMkRqkAAk

```

Explanation:

```
DAd          def A(d):
Rs           return sum(
f!%dT        filter on condition (not d%T)
r1d          for T in range(1,T)
DMk          def M(k):
R            return
qkAAk        k==A(A(k))

```

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
Ñ¨OÑ¨OQ

```

Try it online!

Pretty straightforward. `Ñ¨` takes the list of divisors without the element itself, `O` sums these up. `Q` checks if after two iterations the result and the input are equal.

Returns 1 if the number is amicable, else 0.

# Answer
> -1 votes
## GolfScript (25 chars)

```
{.{:a,(\{.a\%!*+}/}2*=}:f

```

`a` can, of course, be replaced by the name of any other variable whose contents you don't care about.

---
Tags: code-golf, number-theory
---


# Question
Title: Generate the shortest regex to match these but not those
# Challenge

Given two lists of strings where each string is of length 50 and each list is also of length 50 generate the shortest regex you can that fully matches all the strings in the first list and does not match any of the strings in the second list.

# Scoring

Your score will be the average length of the regexes your program outputs when applied to this file: https://pastebin.com/MvwPbH1G

In this file the lists are separated by a single newline and the pairs of lists by two newlines. Apply your program to each pair twice with once with the first list as the strings to match and once with the second list as the strings to match.

# Rules

* We will use Javascript flavor regexes for simplicity.

# Answer
> 3 votes
# Score: 212.84

```
import re

def ngraphs(ss):
	n = [set() for _ in ss[0]]
	for s in ss:
		for i in range(1, len(s) + 1):
			for j in range(len(s) - i + 1):
				n[i - 1].add(s[j:j + i])
	return n

while True:
	y = [input() for _ in " " * 50]
	input()
	n = [input() for _ in " " * 50]
	input()
	input()
	yngraphs = sum([sorted(a - b) for a, b in zip(ngraphs(y), ngraphs(n))], [])
	regex = yngraphs.pop(0)
	while not all(re.search(regex, a) for a in y):
		regex += "|" + yngraphs.pop(0)
	print("^.*(" + regex + ").*$")
	print()

```

Try it online!

A pretty uninteresting brute-force solution. Only uses alphanumeric characters and `|`, so a) flavor doesn't really matter b) I expect this to be easily beaten by a smarter brute-force solution at least.

# Answer
> 1 votes
# Python 3, score 122.39

```
count = 0
total = 0
while True:
    y = [input() for _ in range(50)]
    input()
    n = [input() for _ in range(50)]
    input()
    input()
    s = set()
    for x in y:
        i = 1
        while any(a[:i] == x[:i] for a in n):
            i += 1
        s.add(x[:i])
    regex = "^(" + "|".join(s) + ").*"
    count += 1
    total += len(regex)
    print(regex)
    print(total / count)

```

Try it online! Explanation: Simply takes the set of minimal prefixes of the strings in the first list that aren't prefixes of any strings of the second list and uses that to build a regex.

---
Tags: code-challenge, regular-expression, code-generation, test-battery
---


title: Elevator sequence

text:
# Question
Title: Elevator sequence
Totally not inspired by Lyxal repeatedly mentioning elevators in chat :P

## Challenge

In short: simulate some people filling up an elevator and then leaving it.

The elevator is simplified as a grid, where each person can occupy one cell of the grid. The height and width of the grid is the input parameter. The width is always odd, and it has an opening of 1 unit width at the center of the top side. The following diagram shows an elevator of width 5 and height 4, initially empty:

```
+------   ------+
| ?  ?  ?  ?  ? |
| ?  ?  ?  ?  ? |
| ?  ?  ?  ?  ? |
| ?  ?  ?  ?  ? |
+---------------+

```

Now, 20 people, numbered 1 to 20 in the order of boarding, start filling up the elevator. People tend to stick to the front, but cannot block other people boarding when some spots are still empty. As a simplification, let's simply assume that people fill the spots in the left-right-left-right fashion from the frontmost row, leaving the middle column empty (which is then filled by the last few people):

```
+------    ------+
|  1  3 20  4  2 |
|  5  7 19  8  6 |
|  9 11 18 12 10 |
| 13 15 17 16 14 |
+----------------+

```

When people leave the elevator, they do row-by-row, starting with the center column and then alternating left and right sides. So the order of leaving is as follows:

```
20, 3, 4, 1, 2, 19, 7, 8, 5, 6, 18, 11, 12, 9, 10, 17, 15, 16, 13, 14

```

The challenge is to **produce this sequence** for given width and height of the elevator (again, the width is guaranteed to be odd).

You can use 0-based numbering instead of 1-based.

I/O applies. The I/O format can be in one of three ways:

* Take width and height, and output the full sequence
* Take width, height, and index (0- or 1-based), and output the n-th number (index is guaranteed to be valid)
* Take width, height, and n (at most the number of cells), and output the first n numbers

The standard rules apply. The shortest code in bytes wins.

## More test cases

```
width = 1, height = 1
output = 1

width = 1, height = 10
output = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

width = 9, height = 1
output = 9, 7, 8, 5, 6, 3, 4, 1, 2

width = 7, height = 5
output = 35, 5, 6, 3, 4, 1, 2, 34, 11, 12, 9, 10, 7, 8, 33, 17, 18,
15, 16, 13, 14, 32, 23, 24, 21, 22, 19, 20, 31, 29, 30, 27, 28, 25, 26

```

# Answer
# Jelly, 12 bytes

```
p1Ṛ;@pỤɓḊU^1

```

Try it online!

Takes (height, width) arguments and returns the sequence.

Unrelated String saved two bytes. Thank you!

## Explanation for (width, height) = (7, 5)

`ḊU^1` is `[width..2]` each XORed with `1`: `[6,7,4,5,2,3]`.

We take the Cartesian `p`roduct of `[1..height]` and that. The result is a list of `6×5` pairs:

```
[[1,6], [1,7], [1,4], [1,5], [1,2], [1,3],
 [2,6], [2,7], [2,4], [2,5], [2,2], [2,3],
 [3,6], [3,7], [3,4], [3,5], [3,2], [3,3],
 [4,6], [4,7], [4,4], [4,5], [4,2], [4,3],
 [5,6], [5,7], [5,4], [5,5], [5,2], [5,3]]

```

Then, `p1Ṛ;@` appends `[[5,1],[4,1],[3,1],[2,1],[1,1]]` to this list, for a total of `7×5` pairs.

```
[[1,6], [1,7], [1,4], [1,5], [1,2], [1,3],
 [2,6], [2,7], [2,4], [2,5], [2,2], [2,3],
 [3,6], [3,7], [3,4], [3,5], [3,2], [3,3],
 [4,6], [4,7], [4,4], [4,5], [4,2], [4,3],
 [5,6], [5,7], [5,4], [5,5], [5,2], [5,3], [5,1], [4,1], [3,1], [2,1], [1,1]]

```

Wow, this all seems like it's getting us nowhere! But:

* The lexicographically smallest element `[1,1]` is found at index `35`,
* and the second smallest element `[1,2]` is at index `5`,
* and the third smallest element `[1,3]` is at index `6`,
* ...
* and the largest element `[5,7]` is at index `26`.

so in other words, the "grade"  is an elevator sequence, and we're done.
> 15 votes

# Answer
# Python 2, ~~75~~ ~~69~~ ~~50~~ ~~48~~ 45 bytes

```
lambda w,h,i:[w*h+~i/w,1^~i%w+i/w*~-w][i%w>0]

```

Try it online!

*-6 bytes thanks to a suggestion from @dingledooper to persue a single for loop*

*-2 bytes from following a lead from @Arnauld*

*-3 bytes from @dingledooper*

Outputs the sequence as 0-based instead of 1-based.

Given a (0-based) index i, this returns the i-th entry of the sequence as per tag defaults.

> Format: The answers can use one of the following input/output methods: ∘ Given some index n it can return the n-th entry of the list. ∘ ...

Notes: `~y == -y - 1`, `~-w == w-1` (avoids parentheses), and two-argument bitwise operators have very low precedence, so `w-i%w-1^1 = (w-i%w-1)^1`.
> 9 votes

# Answer
# JavaScript (ES6), 39 bytes

Expects `(w, h, n)` and returns the n-th term. Everything is 0-indexed.

```
(w,h,n,y=n/w)=>n%w?-n%w-~y*~-w^1:w*h+~y

```

Try it online!
> 5 votes

# Answer
# , 37 36 bytes

```
,@(_2|.\|.)"1@i.@(,<:),@,.~[{.i.@-@*

```

Try it online!

Returns the full sequence.

Zips the last "height" elements, reversed, with the remaining elements taken in rows of "width - 1", with each row re-arranged by reversing it, and then taking chunks of 2 and reversing each of those. The resulting matrix is flattened.
> 5 votes

# Answer
# Jelly, ~~18~~ 17 bytes

```
×µð_ḶœsḂ_$Þ€ż@_ⱮF

```

Try it online!

*-1 byte trading one dyad-identity-dyad chain for another*

Width on the left, height on the right. 0-indexed. Still feels a bit golfable. Ties the similar, arguments-reversed `_ḶœsḂ_$Þ€ż@_ⱮFð@×`. (Speaking of tying, take a peek at the edit history for a good laugh.)

```
×                    Let the product of the arguments
 µð                  be the left argument to the following dyadic chain:

   _Ḷ                [0 .. product-height-1]
     œs              split into as many slices as the height.
          Þ€         Sort the elements of each ascending by
       Ḃ_$           (x % 2) - x.
            ż@       Interleave the slices after each
              _Ɱ     product - each [1 .. height],
                F    and flatten to obtain the sequence.

```
> 5 votes

# Answer
# Jelly, 34 bytes

```
R}Uð×RœṖ@’×‘ɗœsL}¹;"U}¥ʋ/s€2Ṛ€FðỊ?

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 67 bytes

```
w=>h=>(g=c=>[c?w*r-r-c^1:w*h-r,...++c-w?g(c):r++-h?g(0):[]])(0,r=1)

```

Try it online!
> 3 votes

# Answer
# Japt, ~~26~~ ~~24~~ 23 bytes

Ugly as all hell and almost certainly golfable but it does the job without need for a mathematical formula.

Takes height as the first input, width as the second and outputs the full sequence.

```
N×õ
oNg)íUòVÉ mò mw)c f

```

Try it

```
N×õ\noNg)íUòVÉ mò mw)c f     :Implicit input of integers U=height & V=width
N                            :The array of all inputs (i.e [U,V])
 ×                           :Reduce by multiplication
  õ                          :Range [0,N×]
   \n                        :Reassign to U
     o                       :Remove and return the last
      Ng                     :  First element of N (i.e., original U) elements
        )                    :End remove
         í                   :Interleave
         Uò                  :  Partitions of the remaining elements of U of length
           VÉ                :    V-1
              m              :  Map
               ò             :    Partitions of length 2
                 m           :  Map
                  w          :    Reverse
                   )         :End interleave
                    c        :Flatten
                      f      :Filter

```
> 3 votes

# Answer
# Charcoal, 29 bytes

```
ＮθＮηＦηＩＥθ⎇κ⁺⁻×⊖θ⊕ικ⊗¬﹪κ²⁻×θηι

```

Try it online! Link is to verbose version of code. Outputs the 1-indexed list. Explanation:

```
ＮθＮηＦη

```

Input the width and height and loop over each row of the lift.

```
ＩＥθ⎇κ

```

Loop over each column of the lift; ...

```
⁺⁻×⊖θ⊕ικ⊗¬﹪κ²

```

... the columns leave in swapped pairs, ...

```
⁻×θηι

```

... but the centre column of the row leaves first.

Example for the 3rd (0-indexed row `i=2`) row of the `7×5` lift: the 0-indexed column variable `k` loops from `0` to `6`; `0` gets mapped to the centre column, which is `7×5-i=33`, while the columns `1` to `6` get mapped first to `6×3-k` or `17, 16, 15, 14, 13, 12`, but 2 is then added to alternate terms, yielding the desired result `17, 18, 15, 16, 13, 14`.
> 2 votes

# Answer
# Vyxal `R`, 13 bytes

```
ɽ›Ṙ1꘍Ẋ⁰1v"ṘJ⇧

```

Try it Online! Returns 0-indexed.

A port of Lynn's excellent Jelly answer - go upvote that, and have a look at their explanation, which is much better than this. Returns 0-indexed.

```
ɽ›Ṙ           # Width...2
   1꘍         # xor 1
     Ẋ        # Cartesian product with 1...height
      ⁰       # 1...height
       1v"    # Each paired with 1
          Ṙ   # Reverse
           J  # Append that to the previous
            ⇧ # Grade

```
> 2 votes

---
Tags: code-golf, sequence, grid
---


# Question
Title: Pixel-art, episode 1: display Super Mario
it's a-me!

Today's task is simple: write a program, or a function that displays the idle small Mario sprite, from Super Mario Bros, on NES, over a blue background.

Any kind of entry is valid as long as it displays those 12 * 16 pixels anywhere on the screen / window / browser.

(EDIT: the displayed image can be scaled up if your language can't do pixel art. You can also output ASCII art or HTML art, but using the right colors.)

Image (zoomed 400%):

You must use the following colors:

* blue: #6B8CFF
* red: #B13425
* green/brown: #6A6B04
* orange: #E39D25

Shortest program (in number of characters) wins!

Standard loopholes apply (especially, no network connexion allowed), but hardcoding and displaying an image file in your program is allowed. (entries using this trick will be rank separately)

Here we go!

---

# Current Leaderboard

**Shortest answer using code only:**

**Shortest answer using some kind of hardcoded image:**

# Answer
# HTML/JS, ~~206~~ ~~158~~ ~~153~~ 102

**102**

Trick used: save the compressed GIF file as an HTML file, and add \ at the end

Thanks to this entry: https://codegolf.stackexchange.com/a/39926/10732 by @NiettheDarkAbsol

```
GIF87a  ¡ kŒÿã%jk±4%,       6„‡héj„Af-ÕdÎy\%    …R˜0”ŒÈJ³I©±²û“ú=ª$±p%i¸•¤ <img src=#>

```

Demo: http://meuziere.free.fr/mario/gif.html

Older versions:

**153**

Trick used: save the compressed PNG file as an HTML file, and add \ at the end

```
‰PNG

IHDR         _v”   PLTEjkkŒÿ±4%ã%ó’V   IIDAT×c[Êµj%C€ÍUŸ?|ìíœÿ02„ÿÿÊÐÊàÐÄÈÀ°ŠáÓë~†«ö3üZµž!jÚR‡P x( s6ïåÇ<img src=#>

```

**158**

Trick used: setting the trimmed dataURI of a compressed PNG as the SRC of an IMG tag and packing the whole thing in Unicode chars.

Execute that in your JS console:

```
document.write(unescape(escape('').replace(/uD./g,'')))

```

**206**

Unpacked (206b):

```
<img src=data:image;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAQAgMAAABfD3aUAAAADFBMVEVqawRrjP+xNCXjnSXzkghWAAAASUlEQVQI12MIWxXKELVqJUOAzVUGnz9/GXzs7Rmc/zAyhP//yhDQEMrg0MTIwLCKgeHT636Gf6v2M/xatZ4hatpSBodQoHgoAw>

```

Demo

Tools used:
> 36 votes

# Answer
## Mathematica, ~~412~~ ~~292~~ ~~252~~ ~~212~~ ~~163~~ ~~148~~ ~~143~~ 141 characters

```
f=FromDigits[ToCharacterCode@#,2^16]~IntegerDigits~#2&;Image@Partition[f["넴╫賿橫ӣ鴥",256][[3#+1;;3#+3]]/256&/@"吀啐^A媾핮﻽溿뽫ﺩ埿⩕樨ꦪª⿼?ཐᐅ橕ꦪ喪"~f~4,12]

```

This uses caret notation `^A` for the control character at code point `1`. In Mathematica, I can actually embed the character literally, although that leads to all sorts of ugliness when copying things around. Anyway, the above is 2 characters shorter than my former version, and I got those to characters from using base-4 instead of base-5 to encode the colour palette indices. Right now I cannot be bothered to fix the explanation and screenshot below, so I'm leaving you here with the original base-5 version of my answer:

---

```
f=FromDigits[ToCharacterCode@#,2^16]~IntegerDigits~#2&;Image@Partition[f["넴╫賿橫ӣ鴥",256][[3#-2;;3#]]/256&/@"ᯱ曎㌟뱮䚻륏Σ襺ﺦ您汜豈塘ᙉ雬儥衰ꐰꃾ纔ㆯ쭴뫋澖ᕿ蓉"~f~5,12]

```

I'm encoding the pixels in Unicode characters (yay for counting by characters!).

Here is what it looks like in Mathematica:

Here's how it works:

First we define a function `f` that turns Unicode strings (passed in as the first argument `#`) into lists of integers. First we obtain the character codes. Those can be interpreted as digits of a base 65536 number. And then we convert that number to another base, passed in as the second argument `#2`.

Now let's do that for the longer Unicode string. `ToCharacterCode` yields this list:

```
{7153, 26318, 13087, 48238, 18107, 47439, 931, 35194, 62191, 65190, \
 24744, 57782, 27740, 35912, 22616, 5705, 38636, 20773, 34928, 42032, \
 41214, 32404, 12719, 52084, 47819, 28566, 5503, 33993}

```

Treating this as base 65536:

```
7933607912575313477287527915733176998797205587959732019781370103381...
4831246938139171755469819519515972565671101475553962564506286523593

```

And converting to base 5:

```
{2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
 2, 2, 2, 3, 3, 3, 4, 4, 3, 4, 2, 2, 2, 2, 3, 4, 3, 4, 4, 4, 3, 4, 4, \
 4, 2, 2, 3, 4, 3, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 4, 4, 4, 4, 3, 3, \
 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 3, 3, 1, 3, 3, 3, \
 2, 2, 2, 2, 2, 3, 3, 3, 1, 3, 3, 1, 3, 3, 3, 2, 3, 3, 3, 3, 1, 1, 1, \
 1, 3, 3, 3, 3, 4, 4, 3, 1, 4, 1, 1, 4, 1, 3, 4, 4, 4, 4, 4, 1, 1, 1, \
 1, 1, 1, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 2, 2, 1, 1, 1, \
 2, 2, 1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 3, \
 2, 2, 2, 2, 3, 3, 3, 3}

```

Those are the colour indices of the pixels, in order blue, red, green, orange. We use those to index into that list of numbers, which is the colour palette.

Now for the colour palette. That's `"넴╫賿橫ӣ鴥"`. We use the above indices to select the correct string. Then we apply our function again, but using base 256. That yields a list of 12 integers:

```
{177, 52, 37, 107, 140, 255, 106, 107, 4, 227, 157, 37}

```

We use `;;` range indexing to pull out the relevant slice for the current colour.

Lastly, we just use `Partition` to split this into rows of `12` and feed it to `Image`. Voilà!

**Edit:** With the Unicode packing the RLE was no longer worth it. Removing it saved 50 characters.

**Edit:** Of course, without RLE, there's also no need to go to base 16.

**Edit:** And while we're at it, why not Unicode-pack the colour palette, too? (I have a hunch that I can save a little bit more by make the entire colour palette also a single string and using `Partition` there too. I'll try that later.)

**Edit:** Yes, that did shave off another 5 bytes.
> 28 votes

# Answer
# Java : ~~398~~ 377

```
void s(){new java.awt.Frame(){public void paint(java.awt.Graphics g){int i=0,x,m[]={12226,44085194,467839834,0x5abea55a,0x5bbd5d50,0x5ffe9540,0x5ffe9540,0x5aee5d50,531408218,334277466,333492170,0xc02fc2},c[]={7048447,0xB13425,6974212,0xE39D25};for(setSize(99,99);i<192;g.setColor(new java.awt.Color(c[m[x]&3])),m[x]/=4,g.drawLine(x+40,60-i%16,x+40,60-i++%16))x=i/16;}}.show();}

```

Simply draws the sprite by unpacking an int for each column. Shown in a full program:

```
class P{
    public static void main(String[]a){
        new P().s();
    }

    void s(){
        new java.awt.Frame(){
            public void paint(java.awt.Graphics g){
                int i=0,x,m[]={12226,44085194,467839834,0x5abea55a,0x5bbd5d50,0x5ffe9540,
                               0x5ffe9540,0x5aee5d50,531408218,334277466,333492170,0xc02fc2},
                          c[]={7048447,0xB13425,6974212,0xE39D25};
                for(setSize(99,99);i<192;
                    g.setColor(new java.awt.Color(c[m[x]&3])),m[x]/=4,
                    g.drawLine(x+40,60-i%16,x+40,60-i++%16)
                )x=i/16;
            }
        }.show();
    }
}

```

Obligatory screenshot:
> 20 votes

# Answer
# x86 Machine Code, 102 bytes

How it works: The image is stored as a 2-bit image using a palette. Each row of the image is stored as 3 bytes, followed by one 1 byte of the color palette. This allows the data to be loaded as a single DWORD. The twelve pixels are output by masking off the lowest 2 bits of the value, writing them to video memory, and then right-shifting the entire value two bits. Once the pixels for the row have been outputted, the palette byte is written to the VGA palette. When the image is finished drawing, the program enters an infinite loop.

Assembly code to generate the binary:

```
org 100h
mov al,13h
int 10h
les ax,[bx]

mov si,image_data
draw:
add di,320-12
lodsd
xchg eax,ebx
mov cl,12
row:
mov ax,bx
and al,3
stosb
shr ebx,2
loop row
xchg ax,bx
mov dx,0x3c9
out dx,al
test al,al
jnz draw

image_data: db 21,0,85,0xb1/4, \
5,0,64,0x34/4,            \
165,190,87,0x25/4,        \
185,191,127,0x6b/4,       \
185,254,254,0x8c/4,       \
233,191,106,0xff/4,       \
213,255,95,0x6a/4,        \
165,168,85,0x6b/4,        \
169,40,106,0x4/4,         \
170,0,170,0xe3/4,         \
47,195,248,0x9d/4,        \
63,0,252,0x25/4,          \
15,0,240,111,             \
5,20,80,111,              \
169,85,106,111,           \
170,85,170

```

Base-64 encoded binary, save it as Mario.com to run it: sBPNEMQHvigBgcc0AWatZpOxDInYJAOqZsHrAuL1k7rJA+6EwHXiwxUAVSwFAEANpb5XCbm/fxq5/v4j6b9qP9X/XxqlqFUaqShqAaoAqjgvw/gnPwD8CQ8A8G8FFFBvqVVqb6pVqg==

Sample output:
> 15 votes

# Answer
# Octo/XO-Chip, 70 bytes

Octo is a high level assembly language that compiles down into bytecoded instructions for the CHIP-8 virtual machine. Octo provides some custom extensions called "XO-Chip" to the basic CHIP-8 bytecode, including the ability to draw 4-color bitmaps via overlaid bitplanes.

The compiled bytes are as follows:

```
0xA2 0x08 0xF3 0x01 0xD0 0x00 0x1F 0x00 0x3F 0xC0 0x39 0x00 0x51 0x00 0x58 0x80
0x21 0xE0 0x00 0x00 0x3F 0x00 0x7F 0xE0 0xFF 0xF0 0x36 0xC0 0x1F 0x80 0x3F 0xC0
0x39 0xC0 0x70 0xE0 0xF0 0xF0 0x00 0x00 0x00 0x00 0x3F 0x80 0x7F 0xE0 0x7F 0xF0
0x3F 0xE0 0x1F 0xC0 0x37 0x00 0x76 0xE0 0xF0 0xF0 0xE9 0x70 0xE0 0x70 0xC0 0x30
0x00 0x00 0x70 0xE0 0xF0 0xF0

```

Run it here in your browser: http://johnearnest.github.io/Octo/index.html?gist=33aa37d4717a425ccd4f

It is probably more illuminating to see the Octo assembly language which produces that bytecode:

```
: main
    i := mario
    plane 3
    sprite v0 v0 0

: mario
    0x1F 0x00 0x3F 0xC0 0x39 0x00 0x51 0x00
    0x58 0x80 0x21 0xE0 0x00 0x00 0x3F 0x00
    0x7F 0xE0 0xFF 0xF0 0x36 0xC0 0x1F 0x80
    0x3F 0xC0 0x39 0xC0 0x70 0xE0 0xF0 0xF0
    0x00 0x00 0x00 0x00 0x3F 0x80 0x7F 0xE0
    0x7F 0xF0 0x3F 0xE0 0x1F 0xC0 0x37 0x00
    0x76 0xE0 0xF0 0xF0 0xE9 0x70 0xE0 0x70
    0xC0 0x30 0x00 0x00 0x70 0xE0 0xF0 0xF0

```

The main program is three two-byte instructions. Set the memory index register `i` to the beginning of the data segment, select drawing plane 3 (3 is a bitmask; this indicates you wish to draw in 4 color mode with both bitplanes) and then draw a sprite at an x and y position given by register `v0` (initialized to zero). The final 0 provides the size of the sprite, which in the SuperChip and XO-Chip instruction sets will draw a 16x16 sprite. In 4 color mode, a bitmap for the first plane is followed immediately by a bitmap for the second plane.

To see how the planes work, consider this modified program which scrolls one plane to the right after drawing mario:

```
: main
    i := mario
    plane 3
    sprite v0 v0 0
    plane 2
    scroll-right
    scroll-right
    scroll-right
    scroll-right

: mario
    0x1F 0x00 0x3F 0xC0 0x39 0x00 0x51 0x00
    0x58 0x80 0x21 0xE0 0x00 0x00 0x3F 0x00
    0x7F 0xE0 0xFF 0xF0 0x36 0xC0 0x1F 0x80
    0x3F 0xC0 0x39 0xC0 0x70 0xE0 0xF0 0xF0
    0x00 0x00 0x00 0x00 0x3F 0x80 0x7F 0xE0
    0x7F 0xF0 0x3F 0xE0 0x1F 0xC0 0x37 0x00
    0x76 0xE0 0xF0 0xF0 0xE9 0x70 0xE0 0x70
    0xC0 0x30 0x00 0x00 0x70 0xE0 0xF0 0xF0

```

If you enjoy this you might like one of my other solutions written with Octo. There's actually a game jam going on for the month of October based around this tool.
> 11 votes

# Answer
# Bash + ImageMagick: ~~350~~ ~~331~~ 321 characters

(Palette shamelessly stolen from Martin Büttner's answer.)

```
p=(B13425 6B8CFF 6A6B04 E39D25)
for c in 21 0 85 5 0 64 165 190 87 1{85,91,27,85} 254{,} 233 191 106 213 255 95 165 168 85 169 40 106 170 0 170 47 195 248 63 0 252 15 0 240 5 20 80 169 85 106 170 85 170;{
for j in 0 2 4 6;{
d+=(-fill \#${p[c>>j&3]} -draw point\ $[i%12],$[i++/12])
}
}
convert -size 12x16 xc: "${d[@]}" x:

```

Sample output:

To inspect it easily add `-scale 120` to `convert`'s parameters to get a 10x scaled version:
> 10 votes

# Answer
# GIF - 93 bytes

Hardcoding the image is apparently okay now, so... yay? :D

```
GIF87a  ¡ kŒÿã%jk±4%,       6„‡héj„Af-ÕdÎy\%    …R˜0”ŒÈJ³I©±²û“ú=ª$±p%i¸•¤  ;

```

As seen in Notepad++

# As PHP - 131 bytes

```
<? header("Content-Type:image/gif");?>GIF87a  ¡ kŒÿã%jk±4%,       6„‡héj„Af-ÕdÎy\%  …R˜0”ŒÈJ³I©±²û“ú=ª$±p%i¸•¤  ;

```
> 10 votes

# Answer
# Groovy 417 386

Fun as hell, but with a terrible char count. GroovyFX needed

```
m=[b:'6B8CFF',r:'B13425',g:'6A6B04',o:'E39D25'];groovyx.javafx.GroovyFX.start{stage(visible:!0){scene(width:60,height:80){flowPane{"3b5r4b2b9r1b2b3g2o1g1o3b1b1g1o1g3o1g3o1b1b1g1o2g3o1g3o1b2g4o4g1b3b7o2b2b2g1r3g4b1b3g1r2g1r3g1b4g4r4g2o1g1r1o2r1o1r1g2o3o6r3o2o8r2o2b3r2b3r2b1b3g4b3g1b4g4b4g".toList().collate 2 each{l->(l[0]as int).times{rectangle(width:5,height:5,fill:"#"+m[l[1]])}}}}}}

```

ungolfed:

```
m=[b:'6B8CFF',
   r:'B13425',
   g:'6A6B04',
   o:'E39D25']

s=5

groovyx.javafx.GroovyFX.start {bd->
  stage(visible: !0) {
    scene(width:s*12, height:s*16) {
      flowPane {
        "3b5r4b 2b9r1b 2b3g2o1g1o3b 1b1g1o1g3o1g3o1b 1b1g1o2g3o1g3o 1b2g4o4g1b 3b7o2b 2b2g1r3g4b 1b3g1r2g1r3g1b 4g4r4g 2o1g1r1o2r1o1r1g2o 3o6r3o 2o8r2o 2b3r2b3r2b 1b3g4b3g1b 4g4b4g"
          .replaceAll(" ", "")
          .toList()
          .collate(2)
          .each { l->
            t=l[0] as int
            cr=m[l[1]]
            t.times {
              rectangle(width:s, height:s, fill:"#"+cr)
            }
          }
      }
    }
  }
}

```
> 6 votes

# Answer
# HTML/JS, ~~427~~ ~~408~~ ~~264~~ ~~256~~ ~~239~~ 226 chars

### Obfuscatweet, ~~271~~ ~~270~~ ~~264~~ ~~256~~ ~~239~~ 226 chars

Using obfuscatweet, managed to shorten this down to \< 250 :D

```
document.write(unescape(escape('').replace(/uD./g,'')))

```

Code below is what this consists of.

Trick used: converted image to base4 String of color tiles, converted this into a hexadecimal String. Index of the base 4 denotes color (0=blue, 1=RED, etc.) CSS with an inline p is used to because divs need content to expand (also p is shorter). Because CSS needs to begin with a letter, 'A' is prepended before the CSS tags.

Padding from the CSS gives pixels. None of this uses Unicode characters, which I'm not too familiar with anyways, though it'd probably go sub-300 in that case. The relative advantage to using the padding is that you can, as in this case, blow up the image to whatever size you want each pixel to be. I've used 9 pixels, but if you spend an extra character, you can get up to 99 pixels per represented pixel.

### CSS, ~~127~~ ~~119~~ ~~118~~ ~~114~~ ~~100~~ ~~13~~ 0 chars

Switching from `p` to `rp` removes the need for `display:inline`, cost +1 char, -15! chars!

Removed all the colors and put it into an array in JS -87 chars. Then I just removed all the css

### JS, ~~300~~ ~~289~~ ~~280~~ ~~275~~ ~~329~~ 325 chars

```
c=["6B8CFF","B13425","6A6B04","E39D25"];a='0155000555540ABEC02EFEFC2EBFBF2BFEA803FFF00A6A002A69A8AA55AAF9D76FFD557FF5555F0541502A00A8AA00AA';with(document)for(i=0;i<96;write('<br>')){h=('000'+parseInt(a.slice(i,i+=6),16).toString(4)).slice(-12);for(j=0;j<12;write('<rp style="padding:1 8;background:#'+c[h[j++]]+'"></rp>'));}

```

I tried to cut as much as I could out of this plain JS processing a hex string, but given as it's my first try, this is how far I got using only what I know. The HTML writing has been shortened by a function that adds tags, and the classes use the base 4 value to determine the color to display.

Using additional shortening, replaced charAt with \[\] brackets, and removed the A0 class and set blue as default color for p, saving additional 10 characters. The additional cost to use `rp` tags is offset by a huge loss in CSS.

Additional offset from removing the while loop pad to just adding '000' for the use case and slicing -12 from it.

Added additional JS for colors, then put the padding in there. Noticed a bug with the padding that requires 2 extra characters to fix. Compacted a bunch of loops

### HTML File, ~~430~~ ~~429~~ ~~419~~ ~~399~~ ~~366~~ 342 chars

Demo

```
<script>c=["6B8CFF","B13425","6A6B04","E39D25"];a='0155000555540ABEC02EFEFC2EBFBF2BFEA803FFF00A6A002A69A8AA55AAF9D76FFD557FF5555F0541502A00A8AA00AA';with(document)for(i=0;i<96;write('<br>')){h=('000'+parseInt(a.slice(i,i+=6),16).toString(4)).slice(-12);for(j=0;j<12;write('<rp style="padding:1 8;background:#'+c[h[j++]]+'"></rp>'));}</script>

```
> 5 votes

# Answer
# MATLAB, 194 193 bytes

The code:

```
imagesc(dec2base(base2dec(reshape('5FVQL5VVVT50A4L4HA594GAHA45A015DAL551G2L41GO101VO0A7FMAANVVAAVVVQ5VLVL40L8100L80',5,[])',32),4)-48);colormap([106 107 4;107 140 255;227 157 37;177 52 37]/255)

```

And the output:

Basically I converted the Mario image so that each pixel is a 2 bit number. I then encoded that in base 32 which is the string shown in the code. This string is first reshaped to be 5 x 16 (each row (12px) of 2bit numbers was encoded into base 32), then converted back into base 10. The result is converted once again, this time into base 4 yielding a 12x16 array of 2 bit numbers. These numbers are plotted using `imagesc()`. Then the colours are assigned using `colormap()` with a custom colour map of the required hex values.

Amusingly, a third of the number of bytes used are just to get MATLAB to set the correct colours *after* it has been plotted. The colour code is almost the same number of bytes as the entire base32 string!.

Without correcting the colour (remove the `colormap()` call), it is **135** bytes, and this is the output for the default colour map on MATLAB R2013a:
> 5 votes

# Answer
# Excel VBA, ~~310~~ ~~307~~ 295 Bytes

Anonymous VBE Immediates Window function that outputs a Mario to the Activesheet object at cells `A1:L16`

```
o=2465251:Cells.RowHeight=48:a[A1:L16],-29589:a[C4:K5,D3:I7,J7,L5,A11:L13],o:a[C3:E3,H3:H4,B4:B6,C6,D4:D5,E5,I5,H6:K6,C8:H8,B9:K10,A10:L10,C11,J11,B15:D16,A16,I15:K16,L16],289642:a[D1:H1,C2:K2,E8:E10,F10:H10,H9,D11:I13,C13:E14,H13:J14],2438321:a[E11,H11],o

```

Helper `Sub`Routine a

```
Sub a(r,c):r.Interior.Color=c:End Sub

```

**Ungolfed Version**

```
Public Sub b()
    o = 2465251
    Cells.RowHeight = 48
    a [A1:L16], -29589
    a [C4:K5,D3:I7,J7,L5,A11:L13], o
    a [C3:E3,H3:H4,B4:B6,C6,D4:D5,E5,I5,H6:K6,C8:H8,B9:K10,A10:L10,C11,J11,B15:D16,A16,I15:K16,L16], 289642
    a [D1:H1,C2:K2,E8:E10,F10:H10,H9,D11:I13,C13:E14,H13:J14], 2438321
    a [E11,H11], o
End Sub

Private Sub a(ByRef r As Range, ByVal c As Integer)
    r.Interior.Color = c
End Sub

```

-3 bytes for removing whitespace -12 bytes for using `[...]` notation over `Range(...)` notation; changing over from hex colors to int colors

## Output
> 5 votes

# Answer
# JavaScript/~~CSS~~/HTML ~~446~~ ~~430~~ ~~407~~ ~~353~~ ~~328~~ 316

I golfed as much as I could and ended up with some dirty HTML/JS, but whatever...it works.

**Edit**: This is it...I'm done.

**Edit** Seriously done this time.

## JavaScript

```
for(i=0;i<192;)document.body.innerHTML+=(i%12?"":"<br>")+"<font color=#"+["6B8CFF","B13425","6A6B04","E39D25"]["000111110000001111111110002223323000023233323330023223332333022333322220000333333300002212220000022212212220222211112222332131131233333111111333331111111133001110011100022200002220222200002222"[i++]]+">█"

```

JSFiddle
> 4 votes

# Answer
## Matlab - ~~449 / 332~~ 305 bytes

partial compression + Using the lower image symetry:

```
a=[0,0];b=[2,2];c=[3,3];d=[a,0];f=[b,2];g=[c,3];h=[b,b];i=[a,a];k=[1,1];l=[0,f,1,2;h,k;c,2,1,3,1;g,k,1;c,k,k;a,k,1,0;0,f,a;h,a];imshow(uint8([d,k,1,k,i;a,k,k,k,k,1,0;a,f,c,2,3,d;0,2,3,2,g,2,g,0;0,2,3,b,g,2,g;0,b,c,c,h,0;d,g,g,3,a;a,b,1,f,i;[l fliplr(l)]]),[107 140 255;177 52 37;106 107 4;227 157 37]/255)

```

-- Partially compressed version (332 bytes):

```
a=[0,0]
b=[2,2]
c=[3,3]
d=[a,0]
e=[1,1,1]
f=[b,2]
g=[c,3]
h=[b,b]
i=[a,a]
imshow(uint8([d,e,1,1,i;a,e,e,e,0;a,f,c,2,3,d;0,2,3,2,g,2,g,0;0,2,3,b,g,2,g;0,b,c,c,h,0;d,g,g,3,a;a,b,1,f,i;0,f,1,b,1,f,0;h,e,1,h;c,2,1,3,1,1,3,1,2,c;g,e,e,g;c,e,e,1,1,c;a,e,a,e,a;0,b,2,i,f,0;h,i,h]),[107 140 255;177 52 37;106 107 4;227 157 37]/255)

```

---

Fully uncompressed version (449 bytes):

```
imshow(uint8([0,0,0,1,1,1,1,1,0,0,0,0;0,0,1,1,1,1,1,1,1,1,1,0;0,0,2,2,2,3,3,2,3,0,0,0;0,2,3,2,3,3,3,2,3,3,3,0;0,2,3,2,2,3,3,3,2,3,3,3;0,2,2,3,3,3,3,2,2,2,2,0;0,0,0,3,3,3,3,3,3,3,0,0;0,0,2,2,1,2,2,2,0,0,0,0;0,2,2,2,1,2,2,1,2,2,2,0;2,2,2,2,1,1,1,1,2,2,2,2;3,3,2,1,3,1,1,3,1,2,3,3;3,3,3,1,1,1,1,1,1,3,3,3;3,3,1,1,1,1,1,1,1,1,3,3;0,0,1,1,1,0,0,1,1,1,0,0;0,2,2,2,0,0,0,0,2,2,2,0;2,2,2,2,0,0,0,0,2,2,2,2]),[107 140 255;177 52 37;106 107 4;227 157 37]/255)

```

---

Output in both cases (magnified on screen obviously, the real one is 12x16pix):
> 4 votes

# Answer
# C, 4999 bytes

This absolutely cannot compete with some of the answers here, but I thought I'd give a C answer a shot. The code is one single long line, so here is a pastebin link. If you'd prefer, here is a base64 encoding of the gzipped code:

`H4sICAzFGFYCA21hcmlvLmMA3Zc9DsIwDIXv0qndUqchkXwUurAgdYiFEEyIu4NYaZBI7PzNT3Lsz4mf408bjdPjct3odh6HVeujdgg4K4vzohCM8esdjHOpkrVoALUtIrBX8y1R04DKNCGZmTp85CVdAHifYuxO3mElIlju6xaRICOgCo4pD64PoiTzHnkZcHYnRhAYcEEpFznxB1mXP4TdS/KeVGYPZbmVaQHlnRVZFi65OkhoGodq+RHrby4xsTj8i6RmapXrPvfa0Q8ZWZY1/UPbSiC7Z2bYA7r0zla57Xmo8sOEzxdNYIXFhxMAAA==`

Notable in that it requires no external libraries to run.

Requires xterm, Konsole, or GNOME terminal, because it uses the RGB expansion to the ANSI color escape codes to output the correct colors (ANSI doesn't define orange). For obvious reasons, ideone won't work. It can be run in Windows under Cygwin, which uses xterm (in fact, that's how I tested it). MSYS might work; I'm not sure.

Output on my machine (xterm):
> 4 votes

# Answer
**Bash 346**

*pure bash with VT100 like escape sequences ( sorry no orange in that palette )*

```
C="  "
B="\033[44m$C"
R="\033[41m$C"
G="\033[42m$C"
O="\033[43m$C"
N="\033[00m\n"
A="BBBRRRRRBBBBNBBRRRRRRRRRBNBBGGGOOGOBBBNBGOGOOOGOOOBNBGOGGOOOGOOONBGGOOOOGGGGBNBBBOOOOOOOBBNBBGGRGGGBBBBNBGGGRGGRGGGBNGGGGRRRRGGGGNOOGRORRORGOONOOORRRRRROOONOORRRRRRRROONBBRRRBBRRRBBNBGGGBBBBGGGBNGGGGBBBBGGGGN"
while read -n1 v
do
  printf "${!v}"
done <<< "$A"

```
> 3 votes

# Answer
# Pyth, 83 bytes

Disclaimer: This isn't a winning candidate, because some of the language features were created after posting the question.

```
.wc16@Lc4CM"±4%kÿjkã%"jC"T\0UP\0Z¾Õnþýn¿¿kþ©WÿõZ*Uj(©ª\0ªøÃ/ü\0?ð\0PjU©ªUª"4

```

Here's a hex-dump:

```
00000000   2E 77 63 31  36 40 4C 63  34 43 4D 22  B1 34 25 6B  .wc16@Lc4CM".4%k
00000010   8C FF 6A 6B  04 E3 9D 25  22 6A 43 22  54 5C 30 55  ..jk...%"jC"T\0U
00000020   50 5C 30 01  5A BE D5 6E  FE FD 6E BF  BF 6B FE A9  P\0.Z..n..n..k..
00000030   57 FF F5 5A  2A 55 6A 28  A9 AA 5C 30  AA F8 C3 2F  W..Z*Uj(..\0.../
00000040   FC 5C 30 3F  F0 5C 30 0F  50 14 05 6A  55 A9 AA 55  .\0?.\0.P..jU..U
00000050   AA 22 34                                            ."4

```

You can also download the program here and run it with

```
python3 pyth.py mario.pyth

```

This creates a file `o.png`:

### Explanation:

There are only 4 different colors, therefore I only need 2 bits to save the color of each pixel.

```
.wc16@Lc4CM"..."jC"..."4
                  "..."   the colors of the image, 2 bit per pixel
                 C        convert these bytes to a number
                j      4  and convert it to base 4 (extracting the colors)
           "..."          the hexcodes of the 4 colors (3 byte per color)
         CM               convert each byte into its number
       c4                 split into 4 lists
     @L                   for each pixel, pick the correct list of color-list
  c16                     split into 16 rows
.w                        save it as "o.png"

```
> 3 votes

# Answer
# Processing 2 - 359 characters

I saw this challenge and immediately thought of Processing's pixel\[\] function. I was hoping it would be shorter but i'm still fairly happy with the result considering this is my first attempt at code golf.

```
int i,l;i=l=0;size(12,16);loadPixels();for(char c:"3b5r6b9r3b3g2o1g1o4b1g1o1g3o1g3o2b1g1o2g3o1g3o1b2g4o4g4b7o4b2g1r3g5b3g1r2g1r3g1b4g4r4g2o1g1r1o2r1o1r1g5o6r5o8r2o2b3r2b3r3b3g4b3g1b4g4b4g".toCharArray()){while(l>0){pixels[i]=#6B8CFF;if(c=='r')pixels[i]=#B13425;if(c=='g')pixels[i]=#6A6B04;if(c=='o')pixels[i]=#E39D25;i++;l--;}if(c<58){l=c-48;}}updatePixels();

```

ungolfed:

```
int i,l;i=l=0;
size(12,16);
loadPixels();
for(char c:"3b5r6b9r3b3g2o1g1o4b1g1o1g3o1g3o2b1g1o2g3o1g3o1b2g4o4g4b7o4b2g1r3g5b3g1r2g1r3g1b4g4r4g2o1g1r1o2r1o1r1g5o6r5o8r2o2b3r2b3r3b3g4b3g1b4g4b4g".toCharArray())
{
    while(l>0)
    {
        pixels[i]=#6B8CFF;
        if(c=='r')pixels[i]=#B13425;
        if(c=='g')pixels[i]=#6A6B04;
        if(c=='o')pixels[i]=#E39D25;
        i++;
        l--;
    }
    if(c<58){l=c-48;}
}
updatePixels();

```

you can download processing here
> 2 votes

# Answer
# Javascript 515

```
str='';
"000111110000|001111111110|002223323000|023233323330|023223332333|022333322220|000333333300|002212220000|022212212220|222211112222|332131131233|333111111333|331111111133|001110011100|022200002220|222200002222"
.split("|").forEach(function(ov, ok) {
str += '<div>'
    ov.split("").forEach(function(iv, ik) {
    str += '<div style="width:1px;height:1px;background-color:' + ['#6B8CFF','#B13425','#6A6B04','#E39D25'][iv] + ';display:inline-block"></div>';
    });
    str+= '</div>';
});
document.write(str);

```

just got it working, still have to go in and golf it up
> 2 votes

# Answer
# Perl - Ungolfed 927

I'll have to golf this later. First time trying out `Image::Magick`.

```
#!/usr/local/bin/perl
use Image::Magick;
use strict;
use warnings;

my @p = (
[0,0,0,1,1,1,1,1,0,0,0,0],
[0,0,1,1,1,1,1,1,1,1,1,0],
[0,0,2,2,2,3,3,2,3,0,0,0],
[0,2,3,2,3,3,3,2,3,3,3,0],
[0,2,3,2,2,3,3,3,2,3,3,3],
[0,2,2,3,3,3,3,2,2,2,2,0],
[0,0,0,3,3,3,3,3,3,3,0,0],
[0,0,2,2,1,2,2,2,0,0,0,0],
[0,2,2,2,1,2,2,1,2,2,2,0],
[2,2,2,2,1,1,1,1,2,2,2,2],
[3,3,2,1,3,1,1,3,1,2,3,3],
[3,3,3,1,1,1,1,1,1,3,3,3],
[3,3,1,1,1,1,1,1,1,1,3,3],
[0,0,1,1,1,0,0,1,1,1,0,0],
[0,2,2,2,0,0,0,0,2,2,2,0],
[2,2,2,2,0,0,0,0,2,2,2,2],
);
my $image = Image::Magick->new;
$image->Set(size=>'12x16');
$image->ReadImage('canvas:white');
for my $i (0..$#p) {
    for (0..(@{$p[$i]} - 1)) {
        my $color;
        $color = ($p[$i][$_] < 1 ? "#6B8CFF" : $p[$i][$_] < 2 ? "#B13425" : $p[$i][$_] < 3 ? "#6A6B04" : "#E39D25");
        print "$i : $_ : $color \n";
       $image->Set("pixel[$_,$i]"=> $color);
    }
}
#$image->Write("mario.png");
$image->Display();

```

I'm sure we have plenty of these but here's mine:
> 2 votes

# Answer
# Bash Printable: ~~179~~ 158 Bytes

Inspired by user2485710's answer.

You need to tune your terminal to match colors exactly.

```
eval "$(base64 -d<<</AD/8AAD9Wm/2amr2Wpq1qlX/qqv9RX/1RRXVQBVpIIaqAAqoAAK8DwP1f9XVf9V|xxd -b -c3 -g0|cut -c10-33|sed $'s/../\e[4$[2#&+1]m \e[0m/g;s/^/echo /')"

```
> 2 votes

# Answer
# Tcl 298

```
package require base64
set d [base64::decode AVUABVVUCr7ALv78Lr+/K/6oA//wCmoAKmmoqlWq+ddv/VV/9VVfBUFQKgCoqgCq]
binary scan $d B* z
set i 0
foreach {a b} [split $z ""] {
if {$i % 12 == 0} {puts "\033\[0m"}
puts -nonewline "\033\[4[string map {00 4 01 1 10 2 11 3} $a$b];m  "
incr i
}
puts "\033\[0m"

```

It's a 2 bits per pixel image in base 64. Pixels are mapped to ansi escape codes.
> 2 votes

# Answer
## JavaScript - 256 characters (161 obfusc-a-tweeted)

```
d=v=>{for(i=v&15;i--;)O.innerHTML+=`<i style="color:#${'6B8CFF6A6B04B13425E39D25'.substr(x%4*6,6)}">█</i>`+(++f%12?'':'<br>');x++},f=x=0,[..."fhilsswsssuss££cgÓdcddc¤g£stcucds³c¹cefefcc¤c§"].map(v=>(d(v=v.charCodeAt(0)-99),d(v>>4)))
```

```
<p id=O>
```

### Method:

1. Using bitmasking, a 63x8-bit string provides a 126x4-bit value array consisting of numbers in the range 0-9. (Frustratingly... saved 63 characters by going 4-bit, but spent 50 characters unpacking the bits again lol. Still, 13 chars is 13 chars! :-)
2. The 4 paint colours are cycled in the order: B, G, R, O. At each iteration, 0-9 divs are rendered for the current color (with a line break every 12th)

To determine the optimal order for the color cycle, I ran the compression algorithm against the raw data for each of 24 permutations of \[R, G, B, O\] and selected the one yielding the shortest output (126 was best, least optimal was around 150-something)

ETA discovered this only after reading the other answers using obfusca-tweet...

```
eval(unescape(escape`ﶈ�`.replace(/u../g,'')))

```

Further ideas. \- Try 3-bit data range 0-6, with the rare 7,8,9 gaining 4 extra each: 60000N. \- check color cycle permutations in all directions and speeds other than horizontally one pixel at a time. \- try multiple render passes so colors can be layered.
> 2 votes

# Answer
# JavaScript ES6 (HTML + CSS), 199 307 3195 3630

Using Obfusc-a-tweet:

```
eval(unescape(escape('').replace(/uD./g,'')))

```

This displays the sprite without using any images or multiple elements; it just misuses the CSS `box-shadow` property to create each pixel. Try it at http://jsbin.com/pozohiyezo/. This unobfuscated version is **307 characters**:

```
s=[]
'39zrp34dfl3jgt14bwu54bkcf47p2h3flyt3inh1454896msoa9pfe79tz5r9d4b334hdx45d496n9gq'.match(/.{5}/g).some((n,i)=>[...parseInt(n,36).toString(4)].forEach((m,j)=>s.push(j+1+'px '+(+i+1)+'px #'+['B13425','6B8CFF','6A6B04','E39D25'][+m])))
document.write('<p style="width:1px;height:1px;box-shadow:'+s+'"')

```

This is the original, plain-vanilla HTML version. See it in action at http://jsfiddle.net/gfeLn1ey/1/.

```
<p style="width:1px;height:1px;box-shadow:4px 1px 0 #B13425,5px 1px 0 #B13425,6px 1px 0 #B13425,7px 1px 0 #B13425,8px 1px 0 #B13425,12px 1px 0 #6B8CFF,3px 2px 0 #B13425,4px 2px 0 #B13425,5px 2px 0 #B13425,6px 2px 0 #B13425,7px 2px 0 #B13425,8px 2px 0 #B13425,9px 2px 0 #B13425,10px 2px 0 #B13425,11px 2px 0 #B13425,12px 2px 0 #6B8CFF,3px 3px 0 #6A6B04,4px 3px 0 #6A6B04,5px 3px 0 #6A6B04,6px 3px 0 #E39D25,7px 3px 0 #E39D25,8px 3px 0 #6A6B04,9px 3px 0 #E39D25,12px 3px 0 #6B8CFF,2px 4px 0 #6A6B04,3px 4px 0 #E39D25,4px 4px 0 #6A6B04,5px 4px 0 #E39D25,6px 4px 0 #E39D25,7px 4px 0 #E39D25,8px 4px 0 #6A6B04,9px 4px 0 #E39D25,10px 4px 0 #E39D25,11px 4px 0 #E39D25,12px 4px 0 #6B8CFF,2px 5px 0 #6A6B04,3px 5px 0 #E39D25,4px 5px 0 #6A6B04,5px 5px 0 #6A6B04,6px 5px 0 #E39D25,7px 5px 0 #E39D25,8px 5px 0 #E39D25,9px 5px 0 #6A6B04,10px 5px 0 #E39D25,11px 5px 0 #E39D25,12px 5px 0 #E39D25,2px 6px 0 #6A6B04,3px 6px 0 #6A6B04,4px 6px 0 #E39D25,5px 6px 0 #E39D25,6px 6px 0 #E39D25,7px 6px 0 #E39D25,8px 6px 0 #6A6B04,9px 6px 0 #6A6B04,10px 6px 0 #6A6B04,11px 6px 0 #6A6B04,12px 6px 0 #6B8CFF,4px 7px 0 #E39D25,5px 7px 0 #E39D25,6px 7px 0 #E39D25,7px 7px 0 #E39D25,8px 7px 0 #E39D25,9px 7px 0 #E39D25,10px 7px 0 #E39D25,12px 7px 0 #6B8CFF,3px 8px 0 #6A6B04,4px 8px 0 #6A6B04,5px 8px 0 #B13425,6px 8px 0 #6A6B04,7px 8px 0 #6A6B04,8px 8px 0 #6A6B04,12px 8px 0 #6B8CFF,2px 9px 0 #6A6B04,3px 9px 0 #6A6B04,4px 9px 0 #6A6B04,5px 9px 0 #B13425,6px 9px 0 #6A6B04,7px 9px 0 #6A6B04,8px 9px 0 #B13425,9px 9px 0 #6A6B04,10px 9px 0 #6A6B04,11px 9px 0 #6A6B04,12px 9px 0 #6B8CFF,1px 10px 0 #6A6B04,2px 10px 0 #6A6B04,3px 10px 0 #6A6B04,4px 10px 0 #6A6B04,5px 10px 0 #B13425,6px 10px 0 #B13425,7px 10px 0 #B13425,8px 10px 0 #B13425,9px 10px 0 #6A6B04,10px 10px 0 #6A6B04,11px 10px 0 #6A6B04,12px 10px 0 #6A6B04,1px 11px 0 #E39D25,2px 11px 0 #E39D25,3px 11px 0 #6A6B04,4px 11px 0 #B13425,5px 11px 0 #E39D25,6px 11px 0 #B13425,7px 11px 0 #B13425,8px 11px 0 #E39D25,9px 11px 0 #B13425,10px 11px 0 #6A6B04,11px 11px 0 #E39D25,12px 11px 0 #E39D25,1px 12px 0 #E39D25,2px 12px 0 #E39D25,3px 12px 0 #E39D25,4px 12px 0 #B13425,5px 12px 0 #B13425,6px 12px 0 #B13425,7px 12px 0 #B13425,8px 12px 0 #B13425,9px 12px 0 #B13425,10px 12px 0 #E39D25,11px 12px 0 #E39D25,12px 12px 0 #E39D25,1px 13px 0 #E39D25,2px 13px 0 #E39D25,3px 13px 0 #B13425,4px 13px 0 #B13425,5px 13px 0 #B13425,6px 13px 0 #B13425,7px 13px 0 #B13425,8px 13px 0 #B13425,9px 13px 0 #B13425,10px 13px 0 #B13425,11px 13px 0 #E39D25,12px 13px 0 #E39D25,1px 14px 0 #6B8CFF,2px 14px 0 #6B8CFF,3px 14px 0 #B13425,4px 14px 0 #B13425,5px 14px 0 #B13425,6px 14px 0 #6B8CFF,7px 14px 0 #6B8CFF,8px 14px 0 #B13425,9px 14px 0 #B13425,10px 14px 0 #B13425,11px 14px 0 #6B8CFF,12px 14px 0 #6B8CFF,1px 15px 0 #6B8CFF,2px 15px 0 #6A6B04,3px 15px 0 #6A6B04,4px 15px 0 #6A6B04,5px 15px 0 #6B8CFF,6px 15px 0 #6B8CFF,7px 15px 0 #6B8CFF,8px 15px 0 #6B8CFF,9px 15px 0 #6A6B04,10px 15px 0 #6A6B04,11px 15px 0 #6A6B04,12px 15px 0 #6B8CFF,1px 16px 0 #6A6B04,2px 16px 0 #6A6B04,3px 16px 0 #6A6B04,4px 16px 0 #6A6B04,5px 16px 0 #6B8CFF,6px 16px 0 #6B8CFF,7px 16px 0 #6B8CFF,8px 16px 0 #6B8CFF,9px 16px 0 #6A6B04,10px 16px 0 #6A6B04,11px 16px 0 #6A6B04,12px 16px 0 #6A6B04,6px 6px 0 5px #6B8CFF"

```
> 1 votes

# Answer
# Javascript, ~~253~~ ~~240~~ ~~238~~ 236

## Obfuscatweeted source - ~~253~~ ~~240~~ ~~238~~ 236

```
document.write(unescape(escape('').replace(/uD./g,'')))

```

## Unobfuscated - ~~395~~ ~~370~~ ~~365~~ 361

```
<script>"5m2o9mh3097log9101pk9zp7u9vtxw93qu8986ww9uogk93csph96jmje96plnu96v7y29m5809thzo93bec5".split(9).forEach(function(c){d=document;c=parseInt(c,36).toString(4);while(c.length<12)c="0"+c;c.split("").forEach(function(v){d.write("<p style='display:inline;padding:9;background:#"+["6B8CFF","6A6B04","E39D25","B13425"][+v]+"'></p>")});d.write("<br>")})</script>

```

Thanks to @compass for the `<p>` tag tricks, and @xem for 2(5) chars.

Demo

It converts data from base 36, and converts to base 4.
> 1 votes

# Answer
## Javascript, ~~256 or 245~~ 252 or 241

**256**

```
document.write("k6n56kcraqlaqasasjaqbsasibtdlstlb2cmc2b2cid5dra2q3q2au7u55rj4j4kclcidld".replace(/./g,function(x){return new Array((x=parseInt(x,36))&7).join("<li style=padding:4%;float:left;background:#"+['B13425','6A6B04','6B8CFF','E39D25'][x>>3]+">")}))

```

It's sad to override 256, but **245** is possible if use nonprintable characters:

```
document.write(btoa(">§ç©ª¥j¦¬jÈÚ©»²&ív[-½ÍÙÈåÚÚÚêÙ«»»køÉ\\Ù]").replace(/./g,function(x){return new Array((x=parseInt(x,36))&7).join("<li style=padding:4%;float:left;background:#"+["B13425","6A6B04","6B8CFF","E39D25"][x>>3]+">")}))

```

There is some problem with submitting solution with nonprintable characters. The argument of `btoa` have to be the result of `atob("ij6n56kcraqlaqasasjaqbsasibtdlstlb2cmc2b2cid5dra2q3q2au7u55rj4j4kclcidld")` with 1 symbol of length added for escaping backslash.

Shorten both solutions by 4 symbols: we don't need new for array creation.

**252**

```
document.write("k6n56kcraqlaqasasjaqbsasibtdlstlb2cmc2b2cid5dra2q3q2au7u55rj4j4kclcidld".replace(/./g,function(x){return Array((x=parseInt(x,36))&7).join("<li style=padding:4%;float:left;background:#"+['B13425','6A6B04','6B8CFF','E39D25'][x>>3]+">")}))

```

**241**

```
document.write(btoa("©ùêG+j©Z©«²6ªnÆ¬»]Ëeog&sför'yv¶¶«z¶jîîçãâ>$rVÚÙ]").replace(/./g,function(x){return Array((x=parseInt(x,36))&7).join("<li style=padding:4%;float:left;background:#"+['B13425','6A6B04','6B8CFF','E39D25'][x>>3]+">")}))

```

No escaping is needed in this version. The `btoa`'s argument is result of `atob("k6n56kcraqlaqasasjaqbsasibtdlstlb2cmc2b2cid5dra2q3q2au7u55rj4j4kclbaidld")`
> 1 votes

# Answer
## Perl, 266 260 257 249 245 bytes

```
$_="444111114444441111111114442223323444423233323334423223332333422333322224444333333344442212224444422212212224222211112222332131131233333111111333331111111133441114411144422244442224222244442222";s/\d/\033[4$&m  /g;s/.{84}/$&\033[00m\n/g;print

```

Uses approach similar to user2485710's bash solution to write a VT100 style output. Strips the explicit N for newline by inserting a newline every 12 "vt100 pixels", 12 * 7 = 84.
> 1 votes

# Answer
# SmileBASIC, ~~147~~ 136 characters

```
P$="xxxxxxxx
FOR I=0TO 191C=ASC("xxxxxxxxxxxxxxxxxxxxxxxx"[I/8])>>I MOD 8*2AND 3GPSET I/16,15AND I,ASC(P$[C*2])<<16OR ASC(P$[C*2+1])NEXT

```

Output (cropped):

I replaced all the characters in the data strings with `x`'s, here are the character codes (in UCS-2):
`P$` (Palette): `FF6B,8CFF,FFB1,3425,FF6A,6B04,FFE3,D925`
Image data: `0000,83F8,0A80,A3FA,8BE4,A5EA,BEA5,A55A,7EE5,0575,BFF5,0156,BFF5,0156,BBA5,0575,3AF4,A55A,3BC4,A5EA,0BC4,A3FA,0300,83F8`

The palette is stored in a string, each color (32 bits) is stored in two characters (16 bits each). The image data (2 bits per pixel) is stored in another string (8 pixels per character)
Luckily, the challenge is scored in characters, since this file is significantly larger if saved in UTF-8.
> 1 votes

# Answer
# 05AB1E, 87 bytes (Non-competing)

```
•8,vkJíÝ1¢tt6,9XÂck$XSãõO©Ú"›qf®¸Ì#}„K0ÝCìxý}É~ð_áú•4BSvy•3«WKyÛòèz*Ðeb•16B6ôè'#ì})12ô»

```

Try it online!

Outputs:

```
#B13425 #B13425 #B13425 #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #B13425 #B13425 #B13425 #B13425
#B13425 #B13425 #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #B13425
#B13425 #B13425 #6A6B04 #6A6B04 #6A6B04 #E39D25 #E39D25 #6A6B04 #E39D25 #B13425 #B13425 #B13425
#B13425 #6A6B04 #E39D25 #6A6B04 #E39D25 #E39D25 #E39D25 #6A6B04 #E39D25 #E39D25 #E39D25 #B13425
#B13425 #6A6B04 #E39D25 #6A6B04 #6A6B04 #E39D25 #E39D25 #E39D25 #6A6B04 #E39D25 #E39D25 #E39D25
#B13425 #6A6B04 #6A6B04 #E39D25 #E39D25 #E39D25 #E39D25 #6A6B04 #6A6B04 #6A6B04 #6A6B04 #B13425
#B13425 #B13425 #B13425 #E39D25 #E39D25 #E39D25 #E39D25 #E39D25 #E39D25 #E39D25 #B13425 #B13425
#B13425 #B13425 #6A6B04 #6A6B04 #6B8CFF #6A6B04 #6A6B04 #6A6B04 #B13425 #B13425 #B13425 #B13425
#B13425 #6A6B04 #6A6B04 #6A6B04 #6B8CFF #6A6B04 #6A6B04 #6B8CFF #6A6B04 #6A6B04 #6A6B04 #B13425
#6A6B04 #6A6B04 #6A6B04 #6A6B04 #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6A6B04 #6A6B04 #6A6B04 #6A6B04
#E39D25 #E39D25 #6A6B04 #6B8CFF #E39D25 #6B8CFF #6B8CFF #E39D25 #6B8CFF #6A6B04 #E39D25 #E39D25
#6A6B04 #6A6B04 #6A6B04 #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6A6B04 #6A6B04 #6A6B04
#6A6B04 #6A6B04 #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6B8CFF #6A6B04 #6A6B04
#B13425 #B13425 #6B8CFF #6B8CFF #6B8CFF #B13425 #B13425 #6B8CFF #6B8CFF #6B8CFF #B13425 #B13425
#B13425 #6A6B04 #6A6B04 #6A6B04 #B13425 #B13425 #B13425 #B13425 #6A6B04 #6A6B04 #6A6B04 #B13425
#6A6B04 #6A6B04 #6A6B04 #6A6B04 #B13425 #B13425 #B13425 #B13425 #6A6B04 #6A6B04 #6A6B04 #6A6B04

```

Because 05AB1E can't do colors, or graphics of any kind... If this isn't acceptable I'll delete it.
> 1 votes

# Answer
# Pxem, 113 bytes (filename).

Here is filename (some characters as backslash with its code point in three-digit octal):

```
xHJG\071\070b\015\001\021\001\242\005\001l\215\400\344\236&kl\005\262\065&-\001\001\001\001\015\001\021\001\001\003\067\205\210i\014\352k\205\015B\005g.\326\030e\317z]&\012\015\206S\231\061\225\215\311K\256\005\264J\252\262\002\263\220\374\224\373>\007\253\007%\262q&j\271\226\245\001\001<.w\001.-.o.c.c.z.d.aX.a

```

Outputs as GIF.

## How it works

Just as @nietthedarkabsol's, but had to add one to every byte, as the original GIF contains null chacters, which is illegal for filename. Then I just decrement each of them to output them. If I had an implementation whose `.w` breaks from the loop when stack is empty (nk. actually specified on the original page but no one has ever complied with it, including himself), then the final part could be golfed to: `.w.o.c.a`.
> 1 votes

# Answer
# Sinclair BASIC - 573 bytes

OK, so the Spectrum can't show RGB colours as specified, so have used the closest possible.

```
10 let x=0:let y=0:let i=0
20 let a$="1c2e1f2i1c4c6b461d4646c46c1b464b6c46c14b6d4d1d6g1d4b24c1e4c24b24c14d2d4d6b4262b6246e2f6e2c1b2c6b1b2c1b2c1c4c1d4c14d1d4d"
30 let l=len a$
40 let i=i+1:let c=1:let p=0:let k=val a$(i)
50 if a$(i+1)>="a" then let c=code a$(i+1)-96:let i=i+1
60 print at y,x;ink k;"\::":let p=p+1:let x=x+1:if x=12 then let x=0:let y=y+1
70 if p<c then goto 60
80 if i<l then goto 40

```

The string is the colour (1=blue, 2=red etc) followed by a letter to represent how many times that block repeats (by taking the ASCII value minus 96 to become 1,2,3 etc). A number without a letter after it just draws one block.

`"\::"` in line 60 is how to enter graphics in a text editor before turning into a TAP file to load into Fuse emulator. (Shows as a solid block graphic on screen).

Each keyword is one byte in Sinclair BASIC, have included a count from a PEEK command after it was generated.
> 0 votes

# Answer
## Perl - 399 171 bytes

```
use MIME::Base64;$_='R0lGODdhDAAQAKEEAGuM/+OdJWprBLE0JSwAAAAADAAQAAACNoSHaAvpaoQMQQRmLdUXZM55XCUJDIVSmDCUjMhKrQSzSamxAbKP+5P6PQaqBiSxcCVpuJWkAAA7';
print decode_base64($_)

```

Writes the gif file to stdout.
> 0 votes

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


title: Days of the Week

text:
# Question
Title: Days of the Week
Create a function that accepts a list of dates (unsorted with possible duplicates) and returns the days of the week in one of the following formats:

* A format similar to `MTWTFSS` or `SMTWTFS` (i.e. beginning with Monday or Sunday), with non-days replaced by an underscore `_`, illustrated below.
* `WEEKDAY` if all the dates are between Monday to Friday (i.e. Monday, Tuesday, Wednesday, Thursday and Friday must all be present, no other days)
* `WEEKEND` if all the dates are on Saturday or Sunday (i.e. Saturday and Sunday must both be present, no other days)
* `ALLWEEK` if all the dates are on all days of the week!

Assume the list of dates to be in your language's date data type (e.g. `List<LocalDate>` for Java), else the ISO date string `"YYYY-MM-DD"`. **Addition: After looking at 05AB1E's entry, I'm now also inclined to accept 'the most convenient representation', but please explain clearly why this would be used in lieu of the original rules. I just don't want to open the flood gates here...**

If it helps, you can further assume that all dates are within an arbitrary calendar non-leap-year.

Examples:

| Input | Output (starting Monday) | Output (starting Sunday) |
| --- | --- | --- |
| `["2021-06-21"]` | `M______` | `_M_____` |
| `["2021-06-21", "2021-06-28"]` | `M______` | `_M_____` |
| `["2021-06-22", "2021-06-22"]` | `_T_____` | `__T____` |
| `["2021-06-23", "2021-07-16"]` | `__W_F__` | `___W_F_` |
| `["2021-06-27", "2021-07-02", "2021-05-01"]` | `____FSS` | `S____FS` |
| `["2021-06-21", "2021-06-22", "2021-06-23", "2021-06-24", "2021-06-25"]` | `WEEKDAY` | `WEEKDAY` |
| `["2021-06-27", "2021-06-26", "2021-06-27"]` | `WEEKEND` | `WEEKEND` |
| `["2021-06-21", "2021-06-23", "2021-06-22", "2021-06-26", "2021-06-25", "2021-06-24", "2021-06-27"]` | `ALLWEEK` | `ALLWEEK` |

Winning Criteria: Shortest code wins.

# Answer
# Japt, 71 bytes

Not happy with this first pass; need to try a few different approaches to see if I can get it down any smaller. ~~Outputs in lowercase, pending confirmation.~~ +3 bytes for the unnecessary requirement of uppercase output.

```
£ÐX eÃÍâ
`³ekÜü³ekÀAa¥³ekmtwtfs`qi o£øY ?X:'_ÃfÏg[Ue5õ)60¥U¬Ô7¥UÊ1]ÃÎu

```

Try it \- includes all test cases
> 3 votes

# Answer
# 05AB1E, ~~93~~ 92 bytes

```
'_7×sε`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%}D.•1ÎÐ³¦•©sèsǝÀÐáÐÙ'sQi'œÙë®¦¦Qi’…Â‚Ž’ëQi’€Ÿ…Â’]u

```

Inputs in the format `[dd,mm,yyyy]`; output format starts at Sunday (`SMTWTFS`).

Try it online or verify all test cases.

**Explanation:**

Since 05AB1E has no Date builtins, we'll have to calculate the *Day of the Week* manually.

The general formula to do this is:

$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$

Where for the months March through December:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month\\$ (`[3, 12]`)
* \\$K\\$ is the year of the century (\\$year \bmod 100\\$)
* \\$J\\$ is the 0-indexed century (\\$\left\lfloor {\frac {year}{100}}\right\rfloor\\$)

And for the months January and February:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month + 12\\$ (`[13, 14]`)
* \\$K\\$ is the year of the century for the previous year (\\$(year - 1) \bmod 100\\$)
* \\$J\\$ is the 0-indexed century for the previous year (\\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\\$)

Resulting in the day of the week \\$h\\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
Source: Zeller's congruence

The implementation of this formula in the code below is:

```
`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%

```

```
'_7×        '# Push string "_______"
s            # Swap to get the (implicit) input-list
 ε           # Map over each date:
             #  Determine its day of the week:
  `          #   Push the day, month, and year to the stack
   U         #   Pop and save the year in variable `X`
    D        #   Duplicate the month
     3‹      #   Check if the month is below 3 (Jan. / Feb.),
             #   resulting in 1 or 0 for truthy/falsey respectively
       ©     #   Store this in variable `®` (without popping)
        12*  #   Multiply it by 12 (either 0 or 12)
           + #   And add it to the month
             #   (This first part was to make Jan. / Feb. 13 and 14)
  >          #   Month + 1
   ₂*        #   Multiplied by 26
     T÷      #   Integer-divided by 10
  ®          #   Push month<3 from variable `®` again
   Xα        #   Take the absolute difference with the year
     ©       #   Store this potentially modified year as new `®` (without popping)
      т%     #   mYear modulo-100
  D4÷        #   mYear modulo-100, integer-divided by 4
  ®т÷©4÷     #   mYear integer-divided by 100, and then integer-divided by 4
  ®·(        #   mYear integer-divided by 100, doubled, and then made negative
  O          #   Take the sum of all values on the stack
   7%        #   And then take modulo-7 to complete the formula, resulting in 0 for
             #   Saturday, 1 for Sunday, and [2, 6] for [Monday, Friday]
}D           # After the map: duplicate the list of integers
  .•1ÎÐ³¦•   # Push compressed string "ssmtwtf"
          ©  # Store it in variable `®` (without popping)
  s          # Swap so the duplicated list of integers is at the top
   è         # Index each into this string
    s        # Swap so the list of integers is at the top again
     ǝ       # Insert the characters at these indices inside the "_______" string
      À      # Rotate it once towards the left
Ð            # Triplicate this result
 á           # Only leave the letters of the top copy
  Ð          # Triplicate that as well
   „ssQi    '# Pop one copy, and if it's equal to "ss":
      'œÙ   '#  Push dictionary string "weekend"
    ë®¦¦Qi   # Else-if it's equal to `®` minus its first two characters ("mtwtf"):
      ’…Â‚Ž’ #  Push dictionary string "weekday"
    ëQi      # Else-if the string remained the same after only leaving letters:
      ’€Ÿ…Â’ #  Push dictionary string "allweek"
    ]        # Close all if-else statements
     u       # Uppercase the result
             # (after which this is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `.•1ÎÐ³¦•` is `"ssmtwtf"`; `'œÙ` is `"weekend"`; `’…Â‚Ž’` is `"weekday"`; and `’€Ÿ…Â’` is `"allweek"`.
> 8 votes

# Answer
# JavaScript (ES6), 119 bytes

Expects a list of `Date` objects. Uses the `SMTWTFS` format.

```
a=>a.map(d=>a|=1<<d.getDay())|a-127?a-62?a-65?'SMTWTFS'.replace(/./g,(c,i)=>a>>i&1?c:'_'):'WEEKEND':'WEEKDAY':'ALLWEEK'

```

Try it online!
> 5 votes

# Answer
# Python 3, ~~223~~ ~~216~~ ~~204~~ ~~200~~ ~~190~~ 186 bytes

Straight forward implementation with `datetime` functions, no fancy string compression.

Saved some bytes exploiting a `dict` for the special cases.

*-4 bytes thanx to Kateba*

```
from datetime import*
m='MTWTFSS'
def f(x,y='_'*7):
 for z in x:i=date.fromisoformat(z).weekday();y=y[:i]+m[i]+y[i+1:]
 return{y:y,m:'ALLWEEK','MTWTF__':'WEEKDAY','_____SS':'WEEKEND'}[y]

```

Try it online!
> 3 votes

# Answer
# PHP, ~~133~~ 132 bytes

```
for($w=SMTWTFS,$r=_______;$d=$argv[++$i];)$r[$j=$d->format(w)]=$w[$j];echo$r==$w?ALLWEEK:$r==_MTWTF_?WEEKDAY:$r==S_____S?WEEKEND:$r;

```

Try it online!

Uses the script arguments array converted to `DateTime` objects (1-indexed), uses the `SMTWTFS` format.

First version with the dict exploit like in movatica's answer, but still looking how to shorten it.

**EDIT:** saved 1 byte with ternary operators
> 2 votes

# Answer
# Perl 5, 155 bytes

```
$o="_"x7;join("",map{strftime"%F%w%A",0,0,0,$_,0,0}0..6e4)=~/$_(.)(.)/,substr$o,$1,1,$2for@F;$_={_MTWTF_,WEEKDAY,S_____S,WEEKEND,SMTWTFS,ALLWEEK}->{$o}||$o

```

Try it online!
> 2 votes

# Answer
# Ruby, 125 bytes

```
f=->l{i=0;l.map{|d|i|=2**d.wday};{i=>(0..6).map{|a|i[a]>0?'SMTWTFS'[a]:?_}*'',62=>'WEEKDAY',65=>"WEEKEND",127=>"ALLWEEK"}[i]}

```

Try it online!

Takes a list of `Date`s and outputs in the `SMTWTFS` format. Abuses Ruby's integer subscriptions to get a (sort of) boolean array.

I copied the dict exploit of the python answer, it works well :)
> 1 votes

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


title: Is IMPLY enough for this function?

text:
# Question
Title: Is IMPLY enough for this function?
Given a boolean function with inputs, check if it's possible to only use IMPLY gate to express it.

There's no extra limitation on how you use this gate, and you can use each input for any amount of times. See examples below:

\\$\begin{matrix} \text{Expression}&&&&&\text{Solution}&\text{Your output}\\ a&0&0&1&1&a&\text{true}\\ b&0&1&0&1&b&\text{true}\\ a\vee b&0&1&1&1&\left(a\rightarrow b\right)\rightarrow b&\text{true}\\ \neg a&1&1&0&0&-&\text{false}\\ a\wedge b&0&0&0&1&-&\text{false}\\ 1&1&1&1&1&a\rightarrow a&\text{true} \end{matrix}\\$

> This actually checks if there is one input that make the output of function true as long as it's true. Proof is left as an exercise.

Input can be taken as a function, a boolean array of length \\$2^n\\$, or any convenient format. Shortest code wins.

# Answer
# Jelly, ~~9~~ 8 bytes

```
oJ’|/‘nL

```

Try it online!

*-1 because it came to me in a dream... to use `>`, which would not have worked at all, but it still got me thinking*

Same input format as hyper-neutrino's solution and also uses OP's spoiler.

```
oJ          Replace each 0 in the input with its index in the input,
  ‘         then decrement each.
oJ‘         We now have every bitmask which yields false, and some extra zeroes.
   |/       Reduce by bitwise OR.
     ‘      Incremented,
      nL    is it not equal to the length?

```

> The bitwise OR of the false bitmasks is 1 less than the length (the length being a power of 2) iff each input variable can produce false while being true.

A rough proof of the spoiler:

> **It is necessary for the function to be implied by a variable:**
> An expression composed of just implications is either a variable or the implication of two such expressions. In butchered BNF: $$\text{\<E\>} \text{ ::= } \text{\<Var\>} \text{ | } \text{\<E\>} \rightarrow \text{\<E\>}$$ Clearly, any expression consisting of a lone variable is true precisely when that variable is true.
> An implication \\$a \rightarrow b\\$, furthermore, is true at least when \\$b\\$ is true, for any expression \\$b\\$. If \\$b\\$ satisfies the property that some variable implies it, so does \\$a \rightarrow b\\$. Therefore this is true of any implication of variables, any implication of implications of variables, and so on.
> **It is sufficient for the function to be implied by a variable:**
> There is no function satisfying the condition which cannot be expressed only in implicatures. Let's call the variable which implies the function \\$a\\$. If we look only at the cases in which \\$¬a\\$, \\$¬b\\$ can be written \\$b \rightarrow a\\$. From there, considering that $$x \vee y \iff (x \rightarrow y) \rightarrow y$$ we have $$x \wedge y \iff ¬(¬x \vee ¬y) \iff (((x \rightarrow a) \rightarrow (y \rightarrow a)) \rightarrow (y \rightarrow a)) \rightarrow a$$ hence any function can be expressed in nothing but implicatures presupposing a known false variable, and such an expression without the presupposition is the disjunction of any function and an additional variable.
> 8 votes

# Answer
# Jelly, 11 bytes

```
;2/ƬḊm2ȦƊ€Ẹ

```

Try it online!

-2 bytes thanks to Unrelated String

Still looking to shorten this with a more intelligent way of applying OP's spoiler. Accepts input as a length \\$2^n\\$ list in the order of `[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]` (standard bit mask enumeration). Working on a proof first though.
> 2 votes

# Answer
# Charcoal, 14 bytes

```
⊙↨⊖Ｌθ²⌊Φθ＆μＸ²κ

```

Try it online! Link is to verbose version of code. Takes input as a binary array of length 2ⁿ and outputs a Charcoal boolean, i.e. `-` for implied, nothing if not. Explanation:

```
    θ           Input array
   Ｌ            Length
  ⊖             Decremented
 ↨   ²          Convert to base 2
⊙               Does any bit satisfy
        θ       Input array
       Φ        Filtered where
          μ     Inner index
         ＆      Bitwise And
           Ｘ²   2 raised to power
             κ  Outer index
      ⌊         Does not contain zero

```
> 2 votes

# Answer
# Japt, 11 bytes

Port of Unrelated String's solution 'cause I genuinely don't have the first clue what the challenge is asking us to do.

```
ÊÉ¦UËÉ©EÃr|

```

Try it or run all test cases

```
ÊÉ¦UËÉ©EÃr|     :Implicit input of array U
Ê               :Length
 É              :Subtract 1
  ¦             :Not equal to
   UË           :Map each element in U at 0-based index E
     É          :  Subtract 1
      ©E        :  Logical AND with E
        Ã       :End map
         r|     :Reduce by bitwise OR

```
> 1 votes

---
Tags: code-golf
---


title: Continuous knapsack but fast

text:
# Question
Title: Continuous knapsack but fast
The input for the continuous knapsack problem is as follows.

For each item 1...n we are given a positive weight and profit. Overall we are also given a positive capacity which is the maximum weight we can carry.

The goal is to pick items so that the profit is maximized without exceeding the capacity. This is hard if you can only pick either 1 or 0 of each item. But in the continuous version we are allowed to pick a fraction of an item as well.

A simple solution is to compute \\$d\_i = p\_i/w\_i\\$ for each item \\$i\\$ (\\$w\_i\\$ is the weight and \\$p\_i\\$ is the profit for item \\$i\\$). We can then sort the \\$d\_i\\$ from largest to smallest, picking each item from biggest to smallest while the capacity has not been reached and possibly a fraction of the final item which is chosen. This take \\$O(n\log n)\\$ time because of the sorting step.

# Examples

```
Capacity 20

Profit Weight
9 6
11 5
13 9
15 7

```

Optimal profit 37.89.

For the optimal solution in this case we have chosen items with profits 11, 15 and 9 to start with. These have total weight 18 and profit 35. We now have 20-2 = 2 left before we reach weight capacity and the only remaining items has weight 9. So we take 2/9 of that item which gives us 2/9 of the profit 13. 35+(2/9)\*13 = 37.8888....

If you increase the capacity to 50, say, then the optimal profit is 9+11+13+15 = 48.

```
Capacity 879

Profit Weight
91 84
72 83
90 43
46 4
55 44
8 6
35 82
75 92
61 25
15 83
77 56
40 18
63 58
75 14
29 48
75 70
17 96
78 32
40 68
44 92

```

The optimal profit is 1036.93.

Here is a larger example:

```
Capacity 995

Profit Weight
94 485
506 326
416 248
992 421
649 322
237 795
457 43
815 845
446 955
422 252
791 9
359 901
667 122
598 94
7 738
544 574
334 715
766 882
994 367
893 984
633 299
131 433
428 682
700 72
617 874
874 138
720 856
419 145
794 995
196 529
997 199
116 277
908 97
539 719
707 242
569 107
537 122
931 70
726 98
487 600
772 645
513 267
81 972
943 895
58 213
303 748
764 487
536 923
724 29
789 674
479 540
142 554
339 467
641 46
196 710
494 553
66 191
824 724
208 730
711 988
800 90
314 340
289 549
401 196
466 865
689 678
833 570
225 936
244 722
849 651
113 123
379 431
361 508
65 585
486 853
686 642
286 992
889 725
24 286
491 812
891 859
90 663
181 88
214 179
17 187
472 619
418 261
419 846
356 192
682 261
306 514
201 886
385 530
952 849
500 294
194 799
737 391
324 330
992 298
224 790

```

The optimal profit in this example is 9279.65.

# Challenge

You can take the input in any form you like although please make it as easy as possible for me to test. Your code must output the optimal profit correct to within +- 0.01.

Most importantly, your code must run in **linear** time. This means you cannot use sorting to solve the problem. Your code can be either worst case linear or expected running linear.

However, this is still a challenge, so the shortest submission in bytes per language wins, but the complexity is restricted to linear.

# Answer
# Python 3, ~~332~~ \\$\cdots\\$ ~~242~~ 252 bytes

```
from random import*
def f(l,W):
 a,b=choice(l);L=*M,=*S,=[]
 for p,w in l:[[M,S][p/w<a/b],L][p/w>a/b]+=(p,w),
 N,X=map(sum,zip(*L+[(0,0)]));A=X
 while X<W and M:*M,(p,w)=M;X+=w;N+=p
 return A>W and f(L,W)or X<W and N+(S>[]and f(S,W-X))or(W-X+w)*p/w+N-p

```

Try it online!

Runs in \\$O(n)\\$ time and space complexity.

Inputs a list of price and weight tuples along with the maximum capacity.
Returns the optimal profit.

Saved 3 bytes thanks to Jakque!!!
Saved 6 bytes thanks to pxeger!!!
Saved 8 bytes thanks to ovs!!!
Added 10 bytes to fix a bug kindly pointed out by Anush.
> 4 votes

# Answer
# Python3, 271 bytes

Runs in expected linear time. Essentially quickselect.

```
from random import *
def k(c,p,V=0):
    while p[1:]!=[]:
        i=randrange(len(p))
        m,l,r=(p[i][0]/p[i][1],i),[],[]
        for j,t in enumerate(p):
            [r,l][(t[0]/t[1],j)>=m]+=[t]
        v,w=map(sum,zip(*l))
        c,V,p=[(c,V,l),(c-w,V+v,r)][w<=c]
    v,w=(p+[(0,1)])[0]
    return V+v*min(c/w,1)

```
> 4 votes

# Answer
# Python 3, ~~394~~ 378 bytes

thanks @Anush for finding issues

thanks @pxeger for -16 bytes

```
def f(x,c):
 A,B=zip(*x);r=len(x);l=o=0
 if c>=sum(B):return sum(A)
 while 1:
  a,b=x[__import__('random').randint(l,r-1)];t=a/b;W=P=0;i=k=l;j=r
  while k<j:
   p,w=x[k];u=v=k
   if p/w>t:v=i;i+=1;W+=w;P+=p
   elif p/w<t:j-=1;v=j;k-=1
   k+=1;x[u],x[v]=x[v],x[u]
  if W>c:r=i;continue
  while W<c and i<j:p,w=x[i];i+=1;W+=w;P+=p
  if W>=c:return(c-W+w)*p/w+P-p+o
  l=j;c-=W;o+=P

```

Try it online!

non-competing. qselect with in-place 3-way partitioning.

`x` list of price-weight pairs

`c` capacity

`l` `r` left and right index in `x` (everywhere it's left inclusive, right exclusive)

`t` pivot

`i` `j` 3-way partitioning:

* `x[l:i]` are larger than `t`
* `x[i:j]` are equal to `t`
* `x[j:r]` are smaller than `t`

`k` current index

`p` price

`w` weight

`P` partial sum of prices

`W` partial sum of weights

`o` accumulator for the result

`u` `v` temporary
> 3 votes

# Answer
# , ~~172~~ 178 bytes

```
f=function(x,m,y=x$p/x$w,s=sample(c(y,y),1),S=sum,i=`if`)i((v=S((z<-x[y>s,])$w))>m,f(z,m),i((t=v+S((u=x[y==s,])$w))>=m,S(z$p)+(m-v)*s,S(c(z$p,u$p))+i(any(y<s),f(x[y<s,],m-t),0)))

```

Try it online!

A function that takes a data frame `x` with columns `w` and `p` and a capacity `m` and returns a double indicating the profit. As far as I can tell, this should be \\$O(n)\\$ complexity. Thanks to @digEmAll for saving 9 bytes! Thanks to @Anush for pointing out that the original version failed where everything can fit in the knapsack.
> 2 votes

# Answer
# C++ (clang), ~~410~~ \\$\cdots\\$ ~~310~~ 302 bytes

```
#import<regex>
using V=std::deque<std::pair<float,int>>;float f(int W,V&l){int N=0,X=0,A=0,i=0;auto[a,b]=l[rand()%l.size()];V L,S,M;for(auto[p,w]:l)(p/w>a/b?N+=p,A=X+=w,L:p/w==a/b?++i,M:S).push_back({p,w});for(;i--&X<W;X+=b)std::tie(a,b)=M[i],N+=a;return A>W?f(W,L):X<W?S>V()?f(W-X,S)+N:N:(W-X)*a/b+N;}

```

Try it online!

*Saved a whopping ~~24 25 31 33 40 44~~ 52 bytes thanks to ceilingcat!!!*

Port of my Python answer.
> 2 votes

# Answer
# Common Lisp, 421 bytes

```
(defun F(F c)(loop for(p w)across(C F)sum p into R sum w into U until(> U c)finally(return(decf R(* p(min(/(- U c)w)1))))))(defun K(f)(floor(apply'/ f).01))(defun C(F)(reverse(let((C(make-array(1+(reduce'max(mapcar'K F))):initial-element 0))(O(make-array(length F))))(mapc(lambda(f)(incf(elt C(K f))))F)(dotimes(i(1-(length C)))(incf(elt C(1+ i))(elt C i)))(mapc(lambda(f)(setf(elt O(decf(elt C(K f))))f))(reverse F))O)))

```

Try it online!

Uses counting sort, should be \\$O(n)\\$ as far as I can tell.

`F` Main function & the list of input items of type `f`

`f` Individual items of format `(profit weight)`

`c` Capacity

`p` Profit of item

`w` Weight of item

`U` Total weight

`R` Total profit

`K` Helper function for calculating \\$\left\lfloor 100\times p\_i/w\_i\right\rfloor\\$ to use as index in `C`

`C` The counting sort & the array `count[k+1]`

`O` The output array in `C`

`i` Generic index
> 2 votes

---
Tags: code-golf, restricted-complexity
---


title: Tips for Golfing in ARM

text:
# Question
Title: Tips for Golfing in ARM
*Because ARM is the July 2021 LoTM, I figured I'd create the tips thread.*

ARM is probably the most successful architecture for the digital world. From mobile phones to supercomputers, ARM is everywhere! Consequently, let's have a thread where we can help each other shorten our ARM code.

One tip per answer, and no stupid tips like "oh remove comments and whitespace".

# Answer
# Use `s` instructions to your advantage.

### ARM

Unlike x86, ARM lets you choose whether to set the condition codes on its instructions, by suffixing the instructions with `s`. This is useful for do-while loops, where you can subtract, do some things, and keep that condition set until you want to branch or conditionally execute.

```
loop:
        // Subtract from r0, set condition codes
        subs    r0, r0, #1
        // idk, do something silly
        ldr     r1, [r0, r2]
        add     r1, r3, r1, lsl #2
        str     r1, [r0, r2]
        // condition codes are still set from subs
        // loop while r0 is not zero
        bne     loop

```

## Thumb-2

This applies in a different way on Thumb-2.

In Thumb-2, most of the narrow instructions always set the condition codes\*, while wide instructions give you the freedom of choice. However, the assembler won't warn you if it is using the wide instruction.

Take the following "Hello World" program:

```
        .syntax unified
        .arch armv6t2
        .thumb
        .thumb_func
        .globl _start
_start:
        mov     r0, #1      // stdout
        adr     r1, .Lhello // "Hello, World!"
        mov     r2, #13     // string length
        mov     r7, #4      // sys_write
        svc     #0          // write(1, "Hello, World!", 13)
        mov     r7, #1      // sys_exit
        svc     #0          // exit(dontcare)
        // UNREACHABLE
.Lhello:
        .ascii "Hello, World!"

```

This is very inefficient, as `mov Rd, #imm` is a wide instruction:

```
00000000 <_start>:
   0:   f04f 0001       mov.w   r0, #1
   4:   f20f 0110       addw    r1, pc, #16 // adr r1, .Lhello
   8:   f04f 020d       mov.w   r2, #13
   c:   f04f 0704       mov.w   r7, #4
  10:   df00            svc     #0
  12:   f04f 0701       mov.w   r7, #1
  16:   df00            svc     #0

```

Instead, if you use `movs` which sets the condition codes, you get a much smaller result:

```
00000000 <_start>:
   0:   2001            movs    r0, #1
   2:   f20f 010c       addw    r1, pc, #12 // adr r1, .Lhello
   6:   220d            movs    r2, #13
   8:   2704            movs    r7, #4
   a:   df00            svc     0
   c:   2701            movs    r7, #1
   e:   df00            svc     0

```

Note: 2 bytes can be saved here by placing this code at an address that is not 4 byte aligned

\*There is one exception. IT blocks.

IT Blocks will prevent condition codes from being set, even on narrow instructions (aside from ones like `cmp` and `tst` where it is pointless not to).

If you are in a situation where you want to chain up to 4 instructions together without setting the condition codes, you can use `it al`.

Note that this is only beneficial for two or more instructions, as IT blocks require an opcode themselves. For only one, it might just be better to use a wide instruction or to `cmp` again.
> 3 votes

# Answer
# ARM/Thumb: Use block loads/stores

`ldm`, `stm`, `push`, and `pop` are pretty cool. They let you load/store multiple registers in order, optionally incrementing or decrementing before or after.

It can be useful for large literal pools instead of a chain of `ldr`s.

In Thumb-2, this also lets you postincrement without a wide instruction.

```
    // *r1++ = r0
    str     r0, [r1], #4 // f841 0b04
    stm     r1!, {r0}    // c101

```
> 1 votes

# Answer
# Thumb: Make sure your literal pools are aligned.

The PC-relative instructions `adr` and `ldr =x` will only be narrow instructions if they are accessing a 4 byte aligned pointer.

Simply reordering things or adding padding can make your literal pools aligned and prevent a wide instruction. This can often create a chain reaction when you have multiple constants, as the act of making one `ldr`/`adr` aligned will change the alignment of other literals, this can be for better or worse.

Another option is to load your code at an address that is **not** 4 byte aligned, so the literal **is** 4 byte aligned. You can typically just put a `nop` at the top of the code to simulate this (assemblers will align your code by default)
> 0 votes

---
Tags: code-golf, tips, machine-code
---