title: Golf a Custom Fibonacci Sequence

text:
# Question
Title: Golf a Custom Fibonacci Sequence
The Fibonacci sequence is a fairly well known thing around here. Heck, it even has its own tag. However, for all that, we sure like to stick to our roots of `1, 1, ...` (or is it `0, 1, ...`? We may never know...). In this challenge, the rules are the same, but instead of getting the `n`th item in the Fibonacci sequence, you will get the `n`th item in the Fibonacci-esque sequence starting with `x, y, ...`.

# Input

Three integers, in whatever order you want. `n` is the index (0 or 1 indexed) of term in the sequence for your output. `x` and `y` are the first two items in your current program run's Fibonacci sequence.

# Output

The `n`th term in the Fibonacci sequence starting with `x`, `y`.

# Test Cases

(0-indexed)

```
n   x     y     out
5   0     0     0
6   0     1     8
6   1     1     13
2   5     5     10
10  2     2     178
3   3     10    23
13  2308  4261  1325165
0   0     1     0
1   0     1     1

```

(1-indexed)

```
n   x     y     out
6   0     0     0
7   0     1     8
7   1     1     13
3   5     5     10
11  2     2     178
4   3     10    23
14  2308  4261  1325165
1   0     1     0
2   0     1     1

```

# Caveats

Assume `0 <= x <= y`.

Please note your input order (must be constant).

# Answer
> 18 votes
# Jelly, 3 bytes

```
+¡ạ

```

Takes **x**, **y**, and **n** (0-indexed) as separate command-line arguments, in that order.

Try it online!

### How it works

```
+¡ạ  Main link. Left argument: x. Right argument: y. Third argument: n

  ạ  Yield abs(x - y) = y - x, the (-1)-th value of the Lucas sequence.
+¡   Add the quicklink's left and right argument (initially x and y-x), replacing
     the right argument with the left one and the left argument with the result.
     Do this n times and return the final value of the left argument.

```

# Answer
> 11 votes
# CJam, ~~14~~ 9 bytes

```
l~{_@+}*;

```

Try it online!

Input format is "x y n". I'm still a noob at this, so I'm 100% sure there are better ways to do this, but please instead of telling me "do this" try to only give me hints so that I can find the answer myself and get better. Thanks!

# Answer
> 9 votes
# JavaScript (ES6), ~~27~~ 26 bytes

Nothing fancy here, just a standard JS Fibonacci function with the initial values of 0 & 1 removed.

```
n=>g=(x,y)=>n--?g(y,x+y):x

```

---

## Try it

```
f=
n=>g=(x,y)=>n--?g(y,x+y):x
o.value=f(i.value=13)(j.value=2308,k.value=4261)
oninput=_=>o.value=f(+i.value)(+j.value,+k.value)
```

```
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
#o{width:75px;}
```

```
<label for=i>n: </label><input id=i type=number><label for=j>x: </label><input id=j type=number><label for=k>y: </label><input id=k type=number><label for=o>= </label><input id=o>
```

# Answer
> 9 votes
# Python 2, 37 bytes

```
f=lambda x,y,n:n and f(y,x+y,n-1)or x

```

Try it online!

0-indexed, you may need to adjust the recursion limit for `n≥999`

# Answer
> 6 votes
## Python 2, 40 bytes

0-indexed
Try it online

```
n,a,b=input()
exec'a,b=b,a+b;'*n
print a

```

# Answer
> 5 votes
# Haskell, 30 bytes

```
x#y=(f!!)where f=x:scanl(+)y f

```

Try it online! 0-indexed. Use as `(x#y)n`, e.g. `(0#1)5` for the fifth element of the original sequence.

The most likely shortest way to get the Fibonacci sequence in Haskell is `f=0:scanl(+)1f`, which defines an infinite list `f=[0,1,1,2,3,5,8,...]` containing the sequence. Replacing `0` and `1` with arguments `x` and `y` yields the custom sequence. `(f!!)` is then a function returning the nth element of `f`.

# Answer
> 5 votes
## Mathematica, 36 bytes

```
LinearRecurrence[{1,1},{##2},{#+1}]&

```

input

> \[n,x,y\]

# Answer
> 5 votes
# PowerShell, 40 bytes

```
$n,$x,$y=$args;2..$n|%{$y=$x+($x=$y)};$y

```

Try it online!

# Answer
> 4 votes
# Brain-Flak, 38 bytes

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

```

Try it online!

```
{({}[()]<                      >)}     # For n .. 0
         (({}<>)<>            )        # Copy TOS to the other stack and add it to...
                  {}                   # The second value
                    <(<>{}<>)>         # Copy what was TOS back
                                  {}{} # Pop the counter and the n+1th result

```

# Answer
> 4 votes
# Ruby, 27 bytes

```
->a,b,n{n.times{b=a+a=b};a}

```

# Answer
> 3 votes
# TAESGL, 4 bytes

```
ēB)Ė

```

1-indexed

**Interpreter**

**Explanation**

Input taken as `n,[x,y]`

```
 ēB)Ė
AēB)     get implicit input "A" Fibonacci numbers where "B" is [x,y]
    Ė    pop the last item in the array

```

# Answer
> 3 votes
# Jelly, 6 bytes

```
;SḊµ¡I

```

Try it online!

**Explanation**

```
   µ¡  - repeat n times (computes the n+1th and n+2th element):
 S     -  take the sum of the elements of the previous iteration (starting at (x,y))
;      -  append to the end of the previous iteration
  Ḋ    -  remove the first element
     I - Take the difference of the n+1th and n+2th to get the n-th.

```

# Answer
> 3 votes
# Prolog (SWI), 85 bytes

```
l(0,X,Y,X).
l(1,X,Y,Y).
l(N,X,Y,C):-M is N-1,P is N-2,l(M,X,Y,A),l(P,X,Y,B),C is A+B.

```

Try it online!

0-indexed.

# Answer
> 3 votes
# Prolog (SWI), 77 bytes

```
f(N,Y,Z):-M is N-1,f(M,X,Y),Z is X+Y.
l(N,A,B,X):-asserta(f(0,A,B)),f(N,X,_).

```

Try it online!

Started off golfing Leaky Nun's answer and arrived at something completely different.

This one has a rule for `(Nᵗʰ, (N+1)ᵗʰ)` in terms of `((N-1)ᵗʰ, Nᵗʰ)` and uses database management to assert 0ᵗʰ and 1ˢᵗ elements at runtime.

`f(N,X,Y)` means `Nᵗʰ` element is `X` and `(N+1)ᵗʰ` element is `Y`.

# Answer
> 3 votes
# R, 39 bytes

```
f=function(x,y,n)'if'(n,f(y,x+y,n-1),x)

```

A simple recursive function. Funnily enough this is shorter than anything I can come up with for the regular Fibonacci sequence (without built-ins), because this doesn't have to assign `1` to both `x` and `y` =P

Calculates `n+1` numbers of the sequence, including the initial values. Each recursion is calculates with `n-1` and stopped when `n==0`. The lowest of the two numbers is then returned, giving back the `n`-th value.

# Answer
> 3 votes
# Octave, 24 bytes

```
@(n,x)(x*[0,1;1,1]^n)(1)

```

Input format: `n,[x,y]`.

Try it online!

# Answer
> 3 votes
# x86 machine code, 7 bytes

`EDX = x = fib[1]`, `EAX = y = fib[2]`, `RCX = n` (1-indexed)
returns in EAX. Works in all 3 modes (16, 32, and 64).
Try it online! (64-bit NASM source with a \_start that parses 3 integers from argv strings)

```
0000000000401070 <cfib>:
  401070:       eb                      .byte 0xeb      # jmp rel8 consuming the 01 add opcode as a rel8
0000000000401071 <cfib.loop>:
  401071:       01 d0                   add    eax,edx
# loop entry point on first iteration, jumping over the ModRM byte of the ADD
  401073:       92                      xchg   edx,eax
  401074:       e2 fb                   loop   401071 <cfib.loop>
  401076:       c3                      ret

```

This "jumps" into the loop with machine code that decodes 2 different ways: with a `jmp +1` when falling into the loop from the top of the function, or with that `01` byte being an ADD opcode when the `loop` instruction jumps backwards. Equivalent to `jmp .entry` but with only 1 byte outside the loop instead of 2.

(Credit to @Ira Baxter for pointing out the general idea of falling into a loop with 1 byte outside that consumes some loop bytes to do something different on the first iteration, e.g. the opcode for `cmp al, imm8` as a 1-byte encoding for a jump forward by 1. I got lucky that `01 add` could be consumed by jmp rel8 to skip a total of 2 bytes without needing a `66` prefix for `cmp ax, imm16` or being in 16-bit mode. 01 or 03 add didn't work well as a modrm for anything like `add r/m32, imm8`; we need to avoid a memory operand. Note that this trick is *not* good for performance on some modern CPUs, e.g. AMD that caches instruction boundaries in L1i tags, and probably not newer Intel/AMD with uop caches.)

Stripping labels lets objdump decode as the CPU would on the first pass:

```
cfib:
  401070:       eb 01                   jmp    0x401073   # jmp rel8 = +1
  401072:       d0                      .byte 0xd0        # jumped over
  401073:       92                      xchg   edx,eax
  401074:       e2 fb                   loop   0x401071
  401076:       c3                      ret

```

It's easy to see that the EDX input will be the EAX return value for ECX=1 (exit right away, `loop` is never taken so `add` never runs).

Use `strace ./custom-fib 14 2308 4261` to see the full integer value passed to the `exit()` system call before truncation to an 8-bit exit status.

In 32-bit mode, the same machine code is callable with GCC regparm(3) calling convention as `__attribute__((regparm(3))) unsigned custom_fib(unsigned y /*eax*/, unsigned x /*edx*/, unsigned n /*ecx*/);`, returning in EAX as usual.

---

## Without the 2-way decode hack: x86 machine code, 8 bytes

0-indexed `n` in RCX, `x` (`fib[0]`) in EAX, y (`fib[1]`) in EDX - note opposite arg order

```
0000000000401070 <cfib>:
  401070:       e3 05                   jrcxz  401077 <cfib.done>
0000000000401072 <cfib.loop>:
  401072:       0f c1 c2                xadd   edx,eax
  401075:       e2 fb                   loop   401072 <cfib.loop>
0000000000401077 <cfib.done>:
  401077:       c3                      ret

```

This way shows off x86's `xadd` instruction, normally only used with a memory destination and a `lock` prefix to implement `fetch_add`.

The reg,reg form of `xadd` decodes to only 3 uops on Intel Skylake, same as `xchg reg,reg` (https://uops.info/). (The `loop` instruction is slow on Intel so this is hardly optimized for speed. If you want a speed-efficient asm implementation, unroll by 2 to remove the xchg as shown in my SO answer using clever loop setup to avoid excess branching for odd vs. even `n` for standard 0,1 Fibonacci.)

# Answer
> 3 votes
# Vyxal, 5 bytes

```
⁽+dḞi

```

Takes input as `[x, y]` then `n`.

Try it online!

Explanation:

```
   Ḟ   # Create an infinite list from the initial vector [x, y] from:
  d    # a dyadic,
⁽      # single element lambda
 +     # which adds its two arguments.
    i  # Index into that list with the second input (n).

```

# Answer
> 2 votes
# Braingolf, 15 bytes

```
VR<2-M[R!+v]R_;

```

`_;` is no longer needed on the latest version of Braingolf, however that's as of ~5 minutes ago. This could be 13 bytes by removing that.

# Answer
> 2 votes
# Python 2, 112 bytes

1-indexed.

```
import itertools
def f(x,y):
 while 1:yield x;x,y=y,x+y
def g(x,y,n):return next(itertools.islice(f(x,y),n-1,n))

```

Try it online!

# Answer
> 2 votes
# PHP\>=7.1, 55 Bytes

```
for([,$n,$x,$y]=$argv;$n--;$x=$y,$y=$t)$t=$x+$y;echo$x;

```

Online Version

# PHP\>=7.1, 73 Bytes

```
for([,$n,$x,$y]=$argv,$r=[$x,$y];$i<$n;)$r[]=$r[+$i]+$r[++$i];echo$r[$n];

```

Online Version

# Answer
> 2 votes
# MATL, 7 bytes

```
:"wy+]x

```

Output is 0-based.

Try it at MATL Online!

### Explanation

Let the inputs be denoted `n` (index), `a`, `b` (initial terms).

```
:"     % Implicitly input n. Do this n times
       %   At this point in each iteration, the stack contains the two most
       %   recently computed terms of the sequence, say s, t. In the first
       %   iteration the stack is empty, but a, b will be implicitly input
       %   by the next statement
  w    %   Swap. The stack contains t, s
  y    %   Duplicate from below. The stack contains t, s, t
  +    %   Add. The stack contains t, s+t. These are now the new two most
       %   recently comnputed terms
]      % End
x      % Delete (we have computed one term too many). Implicitly display

```

# Answer
> 2 votes
# dc, 36 bytes

```
?sdsbsa[lddlb+sdsbla1-dsa1<c]dscxldp

```

Try it online!

`0`-indexed. Input must be in the format `n x y`.

# Answer
> 2 votes
# Common Lisp, 49 Bytes, 0-indexed

```
(defun fib(n x y)(if(= 0 n)x(fib(1- n)y(+ x y))))

```

I'm a Lisp noob so any tips would be appreciated ;)

### Explanation:

```
(defun fib(n x y)                                  | Define a function taking 3 arguments
                 (if(= 0 n)x                       | If n = 0, return x
                            (fib(1- n)y(+ x y))))  | Otherwise, call fib with n-1, y, and x+y

```

# Answer
> 2 votes
# br\**nfuck, ~~39~~ 29 bytes

Thanks to @JoKing for -10!

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

```

TIO won't work particularly well for this (or for any BF solution to a problem involving numbers). I strongly suggest @Timwi's EsotericIDE (or implementing BF yourself).

Takes `x`, then `y`, then `n`. 0-indexed. Assumes an unbounded or wrapping tape.

### Explanation

```
,<,<,            Take inputs. Tape: [n, y, x]
[                While n:
  > [->+>+<<]      Add y to x, copying it to the next cell along as well. Tape: [n, 0, x+y, y]
  < [>+<-]         Move n over. Tape: [0, n, x+y, y]
  >-               Decrement n.
] >>.            End loop. Print cell 2 to the right (x for n == 0).

```

# Answer
> 2 votes
# C (gcc), 29 bytes

```
f(n,x,y){n=n?f(n-1,y,x+y):x;}

```

Try it online!

This implementation is 0-based.

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
`©GDŠ+}®@

```

Try it online!

**Explanation**

```
`           # split inputs as separate to stack
 ©          # store n in register
  G         # n-1 times do
   D        # duplicate top of stack
    Š       # move down 2 places on stack
     +      # add top 2 values of stack
      }     # end loop
       ®@   # get the value nth value from the bottom of stack

```

# Answer
> 1 votes
# Lua, 44 bytes

0-Indexed

```
n,x,y=...for i=1,n do
x,y=y,x+y
end
print(x)

```

Try it online!

# Answer
> 1 votes
# Axiom, ~~88~~ 57 bytes

```
f(k,x,y)==(repeat(k<=0=>break;c:=y;y:=x+y;x:=c;k:=k-1);x)

```

this would pass the test proposed (0 indexed)

```
(14) -> f(5,0,0)
   (14)  0
                                                 Type: NonNegativeInteger
(15) -> f(6,0,1)
   (15)  8
                                                    Type: PositiveInteger
(16) -> f(2,5,5)
   (16)  10
                                                    Type: PositiveInteger
(17) -> f(10,2,2)
   (17)  178
                                                    Type: PositiveInteger
(18) -> f(3,3,10)
   (18)  23
                                                    Type: PositiveInteger
(19) -> f(13,2308,4261)
   (19)  1325165
                                                    Type: PositiveInteger

```

# Answer
> 1 votes
# Klein, 18 + 3 bytes

This uses the `000` topology

```
:?\(:(+)$)1-+
((/@

```

Pass input in the form `x y n`.

# Answer
> 1 votes
# Retina, 37 bytes

```
\d+
$*1
+`(1*) (1*) 1
$2 $1$2
 .*

1

```

Try it online!

0-based, takes `x y n` separated by space. Calculates in unary.

# Answer
> 1 votes
# TI-Basic, 32 bytes

```
Prompt N,X,Y
While N
X+Y➡Z
Y➡X
Z➡Y
DS<(N,0
End
X

```

# Answer
> 1 votes
# k, 15 bytes

```
{*x(|+\)/y,z-y}

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 24 bytes

```
n->x->(x*[0,1;1,1]^n)[1]

```

Input format: `(n)([x,y])`.

Try it online!

# Answer
> 1 votes
# AWK, 39 bytes

```
{for(n=3;n<$1+2;)$++n=$n+$(n-1);$0=$n}1

```

Try it online!

Takes inputs as `n x y` 0-indexed

# Answer
> 1 votes
# Japt, 11 bytes

```
?ß´UWV+W :V

```

Try it online

---

## Explanation

```
(Inputs U, V & W line up with n, x & y in the challenge.)
     :Implicit input of integer U.
?    :Ternary to check if U is currently >0.
ß    :If not, call the function again, with the arguments...
´U   :U-1,
W    :W,
V+W  :and V+W.
:    :Ternary "else", i.e. if U=0
V    :Return V

```

# Answer
> 1 votes
# Java, 58 bytes

```
int f(int n,int x,int y){return n<3?n<2?x:y:f(n-1,y,x+y);}

```

This function is 1-indexed.

Alternatively, one could write the following lambda with recursion, for 55 bytes:

```
interface B{F f=(n,x,y)->n<3?n<2?x:y:B.f.f(n-1,y,x+y);}

```

This requires the following description, which isn't usually counted in Java Lambdas:

```
interface F{int f(int n,int x,int y);}

```

## Test

```
public class Main {

  static
  int f(int n,int x,int y){return n<3?n<2?x:y:f(n-1,y,x+y);}

  public static void main(String[] args) {
    int[][] tests = {
      {6, 0, 0, 0},
      {7, 0, 1, 8},
      {7, 1, 1, 13},
      {3, 5, 5, 10},
      {11, 2, 2, 178},
      {4, 3, 10, 23},
      {14, 2308, 4261, 1325165},
      {1, 0, 1, 0},
      {2, 0, 1, 1}
    };

    for (int[] test: tests) {
      System.out.printf("%2d %4d %4d %7d%n", test[0], test[1], test[2], f(test[0],test[1],test[2]));
    }
  }
}

```

# Answer
> 1 votes
## Mathematica, 25 bytes

Although this is quite old, and there has already been a Mathematica answer using `LinearRecurrence` built-in, mine solution is shorter.

```
{##2}.Fibonacci/@{#-1,#}&

```

# Answer
> 1 votes
# Forth (gforth), 30 bytes

```
: f 1- 0 ?do tuck + loop nip ;

```

Try it online!

Input Order is `x y n`

# Answer
> 1 votes
# Perl 6, 24 bytes

```
{($^x,$^y,*+*...*)[$^n]}

```

Try it online!

# Answer
> 1 votes
# SmileBASIC, ~~44~~ 39 bytes

crossed out 44 is still regular 44 ;(

```
DEF F N,X,Y
IF!N THEN?X
F N-1,Y,X+Y
END

```

Recursive function; prints the result once N reaches 0, ends with a stack overflow.

# Answer
> 1 votes
# Pyth, 23 bytes

```
J.)QWgJlQ=aQ+@Q_2eQ)@QJ

```

**Test suite**

0-indexed, input format: `[x,y,n]`.

# Answer
> 1 votes
# GolfScript, 8 bytes

```
~{.@+}*;

```

Try it online!

Takes input in order `x y n`. Actually generates first *n*+1 values and pops last.

Explanation:

```
~{.@+}*; Full program, implicit input
~        Evaluate
 {   }*  Pop n and repeat:    Stack: x y
  .        Duplicate y               x y y
   @       Get x                     y y x
    +      Add                       y x+y
       ; Pop last

```

# Answer
> 1 votes
# Rockstar, ~~110~~ 105 bytes

```
listen to N
listen to X
listen to Y
cast Y
while N
let Z be X-0+Y
let X be Y
let Y be Z
let N be-1

say X

```

Try it here (Code will need to be pasted in, with each input on an individual line in the order `n`, `x`, `y`)

# Answer
> 1 votes
# APL (Dyalog Extended), ~~16~~ ~~15~~ 13 bytes

```
⊃(1↓⊢,+/)⍣⎕⊢⎕

```

Takes input in the form f x y n

1 fewer byte thanks to TessellatingHeckler

2 fewer bytes thanks to Adám

Try it online!

## Old answer

```
{⊃(1↓⊢,+/)⍣⍺⊢⍵}

```

Takes input in the form n f x y

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

```
n:?
y:?
+?
Fn,z:y,y:x,z+
Oy

```

Try it online!

Just implements the standard Fibonacci algorithm of `x, y = y, x+y` but with `x` and `y` set by the input rather than as \\$0, 1\\$ or \\$1, 1\\$

# Answer
> 1 votes
# Arn, 9 bytes

```
á‹-²À-'Z"

```

Try it! Takes input in order `n, x, y` separated by spaces

# Explained

Unpacked: `[?1_?2{+]?`

```
  [       Begin sequence
      _   Variable initialized to STDIN; implied
    ?     Indexed
      1   Second entry
      _
    ?
      2   Third entry
    {     Block (calculates all other entries)
      +   Last two entries added
    }     End block; implied
  ]       End sequence
?
  _       Implied

```

# Answer
> 1 votes
# Perl 5 `-pl`, 38 bytes

```
($a,$n)=<>;($_,$a)=($a,$a+$_)while$n--

```

Try it online!

Output is 0-indexed. Input format is:

```
x
y
n

```

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

```
:?!v1-}:@+{
{n;>

```

Try it online

**Explanation**

```
:?!v        # if n is 0 move to next row
    1-}     # decrement n and move it to bottom of stack
       :@   # save the largest number for next iteration
         +  # add the current numbers
          { # move n to top of stack
{n;>        # print bottom of stack (smaller number) and exit

```

# Answer
> 1 votes
# Nibbles, 5 bytes (10 nibbles)

```
=@.~~$+<2

```

Input is `[x,y] n`.

```
=@.~~$+<2
  .~~       # append until null (here this means forever)
     $      # starting with first arg
      +     #   sum of
       <2   #   take 2 elements
=@          # finally, get the second-arg-th element

```

---

If we prefer to input `x`, `y` and `n` as individual numbers, instead of combining `[x,y]` as an array, add 1 byte (2 nibbles):

either `=_.~~:$@+<2` (`:$@` combines arg1 and arg2)  or `=+$~.~~_+<2` (`_` treats all args in STDIN as an array, but now we need to add one to the index (`+$~`) since we've prepended a useless value to the start of the sequence)

# Answer
> 0 votes
# cQuents, 8 bytes

```
=A,B:z+y

```

Try it online!

Takes input as `x y n`, where `n` is 1-indexed.

## Explanation

```
=A,B      Set sequence start to first two inputs
    :     Mode: Sequence
     z+y  Each item in the sequence is the previous two added together

          If there is a third input, that input is `n`. Get the `n`th (1-indexed) item in the sequence
          If there is not a third input, output the whole sequence.

```

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


# Question
Title: Evaluate an expression of minus and tilde
Given an expression matching the regex `/^[-~]*x$/`, evaluate it in terms of `x` and output a string matching the regex `/^-?x[+-]\d+$/`.

For example, the string `-~x` evaluates to `x+1`, while the string `-~-x` evaluates to `-x+1`, and the string `-~-~--x` evaluates to `x+2`.

We start from `x` and evaluate the string right to left. `-` negates the term, while `~` converts `y` to `-y-1`.

Testcases:

```
    x  x+0
   ~x -x-1
  -~x  x+1
 ~-~x -x-2
-~-~x  x+2
--~~x  x+0
  ~-x  x-1
 -~-x -x+1

```

This is . Shortest answer in bytes wins.

The input/output format is strict. The `"x"` is mandatory.

# Answer
# Python 2, ~~42~~ ~~41~~ 39 bytes

```
lambda s,x=0:'-x%+d'[len(s)%2:]%eval(s)

```

Try it online!
> 12 votes

# Answer
# Retina, ~~47~~ 44 bytes

```
+`--|~~

((~)|-)*x
$&+$#2
T`+`-`^~.*
~
-
--

```

Try it online! Edit: Saved 3 bytes thanks to @MartinEnder. Expanation:

```
+`--|~~

```

Delete pairs of adjacent duplicates.

```
((~)|-)*x
$&+$#2

```

Count the number of `~`s which gives us the magnitude of the term.

```
T`+`-`^~.*

```

If the first character is a `~` then the term should be negative.

```
~
-
--

```

If the number of `~`s and `-`s is odd then the `x` should be negative.
> 7 votes

# Answer
# JavaScript, 59 bytes

```
x=>['-'[x.length&1]]+'x'+['+'[(x=eval(x.join` `))<0^0]]+~~x

```

Try it online!
> 6 votes

# Answer
# PowerShell Core, 102 bytes

```
$s=-1
switch -r($args[$args.Count..0]){.{$a=-$a;$s=-$s}~{$a--}}"$s`x+$a"|% *ce '+-','-'|% *ce '1x','x'

```

Try it online!

Passes an expression as a string using splatting
Then processes it from right to left
For each char, negate `$s` and `$a`, and if the char is `~` , decrement `$a`
Then concatenate them all: `$s + "x+" + $a`
Replace `+-` with `-`
Remove the useless 1 before x
> 2 votes

# Answer
# C (gcc), 69 bytes

```
a;s;f(char*p){for(a=s=0;*p;a-=*p++%5*~-s)s^=2;printf("-x%+d"+!!s,a);}

```

Try it online!

-1 byte thanks to @ThePirateBay
> 1 votes

# Answer
# Perl 5, 75 + 1 (-n)= 76 bytes

```
map{$y=-$y;$y--if/~/}reverse/-|~/g;printf"%sx%+d",((-1)**y/-~//)=~s/1//r,$y

```

Try it online!
> 1 votes

# Answer
# Ruby, 36 bytes

Port of user48543‘s Python answer.

```
->s{x=0
"-x%+d"[s.size%2..]%eval(s)}

```

Attempt This Online!
> 1 votes

# Answer
# \>\<\> (Fish), ~~91~~ 79 bytes

Was producing incorrect output, but for a change fixing this actually saved me bytes.

```
10>i:'-'=?v:'~'=?vv
 .\r*-10r~<1-@:$~/~
d3/"+"on; .3dv?(0r/
;n^?)-10:o"x"\"-"o/

```

Try this

Significantly harder to parse in reverse order. Basically produce a expression of the form `ax + b`

* For a `-`, set `a` to `-a`.
* For a `~`, set `b` to `b-a`, then re-use the same code to set `a` to `-a`.

Rest of the code is printing the solution. Special cases for printing the `-` in front of `x` and needing a `+` if the extra number is not negative.
> 1 votes

# Answer
# Java 8, ~~186~~ ~~168~~ 167 bytes

```
s->{s=s.replaceAll("--|~~","");int l,i=s.length()-(l=(s=s.replace("-~","")).length())>>1;return(l-(s=s.replace("~","")).length()>0?"-"+s+~i:s+"+"+i).replace("--","");}

```

Definitely room for improvements..

-1 byte thanks to *@ceilingcat* replacing `(a-b)/2` with `a-b>>1`.

Try it online.

**Explanation:**

```
s->{                            // Method with String as both parameter and return-type
  s=s.replaceAll("--|~~","");   //  Remove all "--" and "~~"
  int l,                        //  Temp integer to reduce bytes
      i=s.length()-(l=(s=s.replaceAll("-~","")).length())>>1;
                                //  Remove all "-~" and save count in `i`
  return(l-(s=s.replaceAll("~","")).length()
                                //  Remove all remaining "~"
         >0?                    //  and if its non-empty:
           "-"                  //   Start with a minus sign
           +s                   //   followed by the remaining `s`
           +~i                  //   followed by `-i-1`
          :                     //  Else:
           s                    //   Start with the remaining `s`
           +"+"                 //   followed by a plus sign
           +i                   //   followed by `i`
         ).replaceAll("--","");}//  And then remove all "--"

```
> 0 votes

# Answer
# 05AB1E (legacy), 20 bytes

```
á0:.E…-x+ì„+-¤:IgÉi¦

```

Port of *(deleted) user48543*'s Python answer.

Try it online or verify all test cases.

**Explanation:**

```
á      # Only keep the letters of the (implicit) input (the "x")
 0:    # Replace the "x" in the (implicit) input with "0"
   .E  # Evaluate and execute it as Python code
…-x+ì  # Prepend string "-x+"
„+-¤:  # Replace a potential "+-" with "-"
IgÉi   # If the length of the original input is odd:
    ¦  #  Remove the leading "-"
       # (after which the result is output implicitly)

```
> 0 votes

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


# Question
Title: What's missing (aka the vanilla multiset difference challenge)
Write a program which takes two arrays of positive integers as input. One of them (your choice which) will have one item missing compared to the other. Your program must figure out what is missing.

# Rules

You can choose which array has one missing: You can take ordinary then missing or vice versa.

Arrays may contain duplicates.

# Testcases

```
[1,2,3], [1,3] => 2
[3,3,3,3,3], [3,3,3,3] => 3
[4,6,1,6,3,5,2], [3,6,2,5,4,6] => 1
[9,9,10,645,134,23,65,23,45,12,43], [43,134,23,65,12,9,10,645,45,9] => 23

```

This is , shortest bytes wins!

# Answer
# Python 2, 24 bytes

Takes two lists \\$ a \\$ and \\$ b \\$, where \\$ b \\$ has the missing number.

```
lambda a,b:sum(a)-sum(b)

```

Try it online!

Given that \\$ a \\$ and \\$ b \\$ differ by a single number, we can trivially obtain the answer by computing the difference of sums.
> 21 votes

# Answer
# JavaScript (ES2019), 25 bytes

```
a=>eval(a.flat().join`^`)

```

Try it online!

Take input as `f([array1, array2])`.

Calculate xor of all input numbers.
> 11 votes

# Answer
# Jelly, 2 bytes

```
œ-

```

Try it online!

Just the set difference builtin
> 7 votes

# Answer
# , 19 bytes

```
sum(scan(),-scan())

```

Try it online!

Same idea as dingledooper's Python answer, using R's terser syntax for `sum`. Input is taken from STDIN, with the two multisets separated by a newline.
> 5 votes

# Answer
# Haskell, 12 bytes

```
foldl(-).sum

```

Try it online!

A cooler way to write `(\x y->sum x-sum y)`. For example,

```
    (foldl(-).sum) [4,6,1,6,3,5,2] [3,6,2,5,4,6]
=== (foldl (-) (sum [4,6,1,6,3,5,2])) [3,6,2,5,4,6]
=== (4+6+1+6+3+5+2)-3-6-2-5-4-6
=== 1

```
> 4 votes

# Answer
# JavaScript (ES6), 43 bytes

Expects `(a)(b)`, where `b` has one item missing. Returns a singleton.

This one is a bit overkill and would work with several missing items.

```
a=>b=>b.map(v=>a.splice(a.indexOf(v),1))&&a

```

Try it online!

---

# JavaScript (ES6), 35 bytes

Using dingledooper's sum trick. Same input format. Returns an integer.

```
a=>b=>eval(a.join`+`+'-'+b.join`-`)

```

Try it online!
> 3 votes

# Answer
# Red, 34 bytes

```
func[a b][foreach u b[alter a u]a]

```

Try it online!

~~sum - sum.~~

-4 from dingledooper using the xor trick from tsh.

-15 bytes from Galen Ivanov using his `alter` tip.

# Red, ~~71~~ 63 bytes

```
func[a b][remove-each v a[c: NONE <> find b v replace b v""c]a]

```

Try it online!

Summing is shorter, but really, I just wanted to try using `remove-each`.

Returns a series with a single value (the differing element). Works as a general multiset difference as well.
> 3 votes

# Answer
# Vyxal, 3 bytes

```
v∑¯

```

Try it Online!

Very epic port of the python answer. Takes original and missing in a list.

## Explained

```
v∑¯
v∑  # sum of each list
  ¯ # and deltas

```
> 3 votes

# Answer
# C (gcc), ~~50~~ \\$\cdots\\$ ~~44~~ 43 bytes

Saved ~~5~~ 6 bytes thanks to an idea from AZTECCO!!!

```
c;f(a,b)int*a,*b;{c=*a?f(a+1,b+1)^*a^*b:0;}

```

Try it online!

Inputs \\$2\\$ zero-terminated arrays (since pointers to arrays in C carry no length information) of positive integers with the \\$2^{\text{nd}}\\$ array the same as the \\$1^{\text{st}}\\$ except for a missing number.
Returns the missing number.

### Explanation

Since exclusive-or (\\$\oplus\\$) is associative and commutative, \\$n\oplus n=0\\$, and \\$n\oplus 0=n\\$ we can simply exclusive-or all the numbers from both arrays together to yield the missing number. This is also guaranteed to always fit inside an `int` as no extra bits are ever needed.
> 3 votes

# Answer
# Brachylog, 3 bytes

```
+ᵐ-

```

Try it online!
> 2 votes

# Answer
# Ruby, 18 bytes

```
->a,b{a.sum-b.sum}

```

Try it online!

---

# Ruby, 15 bytes

```
->*a{eval a*?^}

```

Try it online!

Based on tsh's Javascript solution.

Thanks to *@G B* for -3 on the 15 byte solution
> 2 votes

# Answer
# Japt, 5 bytes

```
x)-Vx

```

x : Sums all elements in the array

Try it online!

Same idea as dingledooper's answer.
> 2 votes

# Answer
# Retina 0.8.2, 22 bytes

```
S`,
O`
+`^(.+¶)\1

1G`

```

Try it online! Takes arrays on separate lines but link is to test suite that splits on semicolons for convenience. Works on strings (if they don't contain commas or newlines) as well as integers. Explanation:

```
S`,

```

Split each array into separate strings.

```
O`

```

Sort both arrays.

```
+`^(.+¶)\1

```

Remove leading duplicates.

```
1G`

```

Remove trailing (assumed) duplicates.
> 2 votes

# Answer
# Japt, 5 bytes

Unfortunately, all of Japt's methods for getting the differences between 2 arrays don't take duplicates into account so we have to go with a longer method.

Takes input as a 2D-array, in either order.

```
mx ra

```

Try it
> 1 votes

# Answer
# Julia, 15 bytes

```
a\b=sum([a;-b])

```

Try it online!

similar to dingledooper's answer
> 1 votes

# Answer
# , 5 bytes

```
XOR@,

```

Try it online!

A port of tsh's clever answer.
> 1 votes

# Answer
# yuno, 4 bytes

```
ΣϾ_/

```

Try it online!

Port of the Python solution. I don't have multiset difference built-in yet.

```
ΣϾ_/   ᴋ   Main Link
 Ͼ     ᴋ   For each list
Σ      ᴋ   Take its sum
   /   ᴋ   Then reduce over
  _    ᴋ   Subtraction

```
> 1 votes

# Answer
# Java (JDK), 21 bytes

```
a->b->a.sum()-b.sum()

```

Try it online!
> 1 votes

# Answer
# Factor \+ `math.unicode`, 16 bytes

```
[ [ Σ ] bi@ - ]

```

Try it online!
> 0 votes

# Answer
# MATLAB/Octave, 17 bytes

```
@(a,b)sum([a,-b])

```

Try it online!
Like most of answers here makes use of difference of sums.
MATLAB got its own builtin `setdiff` but for one it doesn't work with multisets just regular sets and for second it's 1 byte longer.
> 0 votes

# Answer
# Japt, 4 bytes

Takes input as an array containing two sub-arrays.

```
c r^
c    // Flatten, then
  r^ // reduce with XOR.

```

Try it here.
> 0 votes

# Answer
# Wolfram Language (Mathematica), 11 bytes

```
Tr@#-Tr@#2&

```

Try it online!

Used algorithm from dingledooper's answer
> 0 votes

# Answer
# Perl 5, 35 bytes

```
$_=pop@F;for$f(@F){s/,$f\b|\b$f,//}

```

Try it online!
> 0 votes

# Answer
# J-uby, 11 bytes

```
:*&:sum|+:-

```

Attempt This Online!

## Explanation

```
:* & :sum | +:-

:* & :sum |      # Map with .sum, then
            +:-  # difference

```
> 0 votes

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


title: UNIX Uniq Uknow?

text:
# Question
Title: UNIX Uniq Uknow?
## Challenge

You must write a program which takes a string and a flag as input and performs one of the following functions.

## Input

If your language does not support command line arguments, you may take the arguments as input via STDIN.

The flag will be two characters: a dash and an ASCII character such as `-d` or `-c`.

## Functions

The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.

### Counting: `-c`

This counts the number of duplicate lines in the input file. For example, if the input is:

```
aa
aa
bb
bb
bb
xx

```

The output will be:

```
2 aa
3 bb
1 xx

```

Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.

### Duplication: `-d`

This shows which lines are duplicates. For example, using the above example string (`aa\naa\nbb\nbb\nbb\nxx`), the output would be:

```
aa
bb

```

Because these are lines which have been duplicated. You should only output each line once.

### Duplication: `-D`

This is almost the same as `-d` except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:

```
aa
aa
bb
bb
bb

```

Because aa occurs twice and bb occurs three times.

### Unique: `-u`

Similar to above except it only prints unique lines. For example, using the example file, the output will be:

```
xx

```

Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.

## Example

Note that although the input string will not always be sorted, ***the output must be sorted alphabetically***. For example, for the following input:

```
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie

```

The output for each of the flags would be:

`-c`

```
4 apple pie
1 dog
2 hello world
1 zebra

```

`-d`

```
apple pie
hello world

```

`-D`

```
apple pie
apple pie
apple pie
apple pie
hello world
hello world

```

`-u`

```
dog
zebra

```

## Rules

Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.

All output should be to STDOUT.

The file will only ever contain lowercase, alphabetical characters, newlines and spaces:

```
abcdefghijklmnopqrstuvwxyz

```

The output should be sorted alphabetically.

In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.

As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.

## Winning

As this is , the shortest code in bytes wins.

# Answer
> 4 votes
## Perl, 92 + 4 (`-sn` flags) = 96 bytes

```
$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h

```

This code needs to be in a file to run. And it needs `-sn` flags, as well as `-M5.010` (free).
For instance :

```
$ cat input.txt
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
$ cat prog.pl
$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h
$ perl -M5.010 -sn prog.pl -c < input.txt
4 apple pie
1 dog
2 hello world
1 zebra

```

# Answer
> 11 votes
## GNU sed, ~~496~~ 485 + 2(rn flags) = 487 bytes

```
1h;1b;$bb;2{:r;$!N;$!br;s/.*/echo "&"|sort/e};:b;x;/[dD]/bd;/c/bc;/u/!b;x;s/^/\n/
s/(\n.*)\1+//g;s/\n//p;b;:d;x;/^(.*)\n\1/!D;:l;x;/D/{x;P;x};x;s/^[^\n]*\n//
/^(.*)\n\1/bl;P;D;:c;s/$/#/;G;x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;:i;s/9(@*:)/@\1/;ti;s/8(@*:)/9\1/;s/7(@*:)/8\1/
s/6(@*:)/7\1/;s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/;s/2(@*:)/3\1/;s/1(@*:)/2\1/
s/0(@*:)/1\1/;s/@+:/1&/;y/@/0/;bc};s/:/ /;s/[^\n]*$/1:&/;bc;:p;x;s/...//;s/..$//;s/:/ /gp

```

The code size is not going to compete, but it was fun emulating the `uniq` command. I wanted to add a simple selection sort to get rid of the `sort` call, thus solving it in pure sed only, but the code got too long already. The input is read entirely from STDIN, with the flag expected on the first line.

**Run:**

```
(echo "-c";cat input_file)|sed -rnf uniq_emulator.sed

```

**Output:**

```
4 apple pie
1 dog
2 hello world
1 zebra

```

**Initially submitted code and explanation:** (sections are separated by an extra newline)

```
# The main
    # store the flag in hold space and start next cycle
1h;1b
    # usually a cycle starts with each line read, but I also start it manually,
    #so I need to skip some lines that should run only once
$bb
2{
        # read the entire input into pattern space
    :r;$!N;$!br
        # executes a shell call to sort the pattern space
    s/.*/echo "&"|sort/e
}
    # based on the flag, the appropriate jumps to "functions" are made
:b;x;/[dD]/bd;/c/bc;/u/!b

# Unique: -u
    # all duplicate lines are deleted and what remains is printed
x;s/^/\n/;s/(\n.*)\1+//g
s/\n//p;b

# Duplication: -d and -D
    # if the first 2 lines are different, delete the first and start new cycle
:d;x;/^(.*)\n\1/!D
:l
        # if -D, print the first duplicate line
    x;/D/{x;P;x};x
        # otherwise (-d), delete the first duplicate line
    s/^[^\n]*\n//
        # loop condition, go back to :l if the first 2 lines are duplicate
/^(.*)\n\1/bl
    # print only the first line and start a new cycle
P;D

# Counting: -c
    # in order to count line occurrences, I simulate reading the input again
    # In a loop I append all pattern space to hold space, delete first line of
    #pattern space and from hold space all lines except the first one appended.
:c;s/$/#/;G
x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
    # if the new line "read" is the same as the previous one, increment the
    #counter of that line (format is "counter:line"), delete and go back to :c
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;bi;:I;bc}
    # otherwise, stop the counter for the previous line, add a counter for the
    #current one and go back to :c
s/:/ /;s/[^\n]*$/1:&/;bc
    # when the loop ends, the hold space with all counts is printed
:p;x;s/...//;s/..$//;s/:/ /gp

# Increment function that works by manually updating the changing digit(s)
:i;s/9(@*:)/@\1/;ti
s/8(@*:)/9\1/;s/7(@*:)/8\1/;s/6(@*:)/7\1/
s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/
s/2(@*:)/3\1/;s/1(@*:)/2\1/;s/0(@*:)/1\1/
s/@+:/1&/;y/@/0/;tI

```

# Answer
> 4 votes
# R, 128 bytes

Using a different method than @Billywob and implemented as a unnamed function

```
function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep='
')}

```

Ungolfed

```
function(s,o){
   R=rle(sort(s));               # do the run length encoding for the sorted input
   cat(                          # output to STDOUT
      switch(o                   # switch on option to provide output lines
        ,'-d'=R$v[R$l>1]         # RLE values with length > 1
        ,'-D'=s[s%in%R$v[R$l>1]] # string values in RLE values with length > 1
        ,'-c'=paste(R$l,R$v)     # RLE length and values pasted together
        ,'-u'=R$v[R$l<2]         # RLE values with length < 2, eg 1
       )
      ,sep='
'                                # set separator to carriage return
   )
}

```

Test Run

```
function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep='
')}
> s = c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie")
> f =
function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep='
')}
> f(s, "-c")
4 apple pie
1 dog
2 hello world
1 zebra
> f(s, "-d")
apple pie
hello world
> f(s, "-D")
hello world
apple pie
hello world
apple pie
apple pie
apple pie
> f(s, "-u")
dog
zebra
>

```

# Answer
> 3 votes
# JavaScript (V8),  ~~170 164~~  140 bytes

Expects `(array_of_strings)(flag_string)`. Prints the output.

```
a=>c=>[...new Set(a)].sort().map(k=>(a.map(v=>n+=v==k,n=0),o={c:n+' '+k,d:n>1&&k,D:n>1&&Array(n).fill(k).join`
`,u:n<2&&k}[c[1]])&&print(o))

```

Try it online!

# Answer
> 3 votes
## R, 179 bytes

```
f=function(s,o){s=sort(s);n="\n";z=cat;for(i in unique(s)){v=sum(s%in%i);if(v>1&o=="-d")z(i,n);if(o=="-c")z(v, i,n);if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="");if(o=="-u"&v<2)z(i,n)}}

```

### Input

Input is assumed to be an "R-vector" of strings (inspired by @Arnauld's JS array input, see below) and a string containing the type of function e.g. `-d`.

### Example

An example of how to execute the function where I pre-define the vector of strings (not necessary).

```
strings <- c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie")

f(strings,"-c")
f(strings, "-d")
f(strings,"-D")
f(strings, "-u")

```

### Ungolfed

```
f=function(s,o){
    s=sort(s)                   # sort vector alphabetically
    n="\n"                      # generate string for newline (used 5x times)
    z=cat                       # generate alias for cat (used 4x times)
    for(i in unique(s)){        # for each unique string of vector
        v=sum(s%in%i)           # count number of occurences
        if(o=="-d"&v>1)z(i,n)   # if occurences >1 & "-d": print each unique string
        if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="") # repeat string #occurences and then print
        if(o=="-u"&v<2)z(i,n)   # if occurences <2 & "-u": print each uniquely occuring string
        if(o=="-c")z(v,i,n)     # if "-c": print number of occurence and each unique string
   }
}

```

I'm sure this can be golfed further by shortening the control flow statements but couldn't figure out a smart way to do it yet.

# Answer
> 2 votes
# Bash(coreutils, grep), 265 bytes

```
IFS=$'\n'
for l in `sort -u $1`;do r=$r$(grep -c "$l" $1)" $l\n"
done
case $2 in -c)printf $r;;-d)printf $r|grep -v "1.*"|cut -d' ' -f2-;;-D)s=$(sort $1)
for l in `sh $0 $1 -u`;do s=$(grep -v "$l"<<<"$s")
done
echo "$s";;-u)printf $r|grep "1.*"|cut -d' ' -f2-;;esac

```

**Usage**

```
$ sh unique.bash input -D
apple pie
apple pie
apple pie
apple pie
hello world
hello world
$ sh unique.bash input -c
4 apple pie
1 dog
2 hello world
1 zebra
$ sh unique.bash input -u
dog
zebra
$ sh unique.bash input -d
apple pie
hello world

```

**Explanation**

* Constructs `$r` which is the output of `-c`. To construct it, it uses `sort -u` which sorts the input file and returns only unique results (I know, somewhat cheat but it wasn't specified in the rules. Feel free to ignore the answer if you don't like it :-). Also, it uses `grep -c` to count the occurrences of each word.
* For `-d` it gets the output of `-c` and with grep it prints everything that does not start with 1. With `cut` it ignores the first column (number of occurrences).
* For `-u` it does exactly the same as `-d` except from `grep`, where it selects everything that starts with 1.
* For `-D` it get the sorted input and remove all the words that are printed with `-u` in a for loop by using `grep -v` again.

# Answer
> 2 votes
# jq -r, 115 bytes

Takes an array of strings and the flag as separate string.

```
group_by(.)|map(select(has(1)))as$m|{c:map("\(length) \(.[0])"),d:[$m[][0]],D:[$m[][]],u:[.-$m|.[][]]}[input[1:]][]

```

Example and explanation:

```
echo '["aa", "aa", "bb", "bb", "bb", "xx"] "-c"' | jq -r '
  group_by(.) |                  # sort and group by item
  map(select(has(1))) as $m |    # store the slice of non-uniques
  {                              # create a lookup object
    c: map("\(length) \(.[0])"), # map to length and one item
    d: [    $m    [][0]],        # take one of each from the slice
    D: [    $m    [][ ]],        # take all of them from the slice
    u: [. - $m | .[][ ]]         # subtract the slice from the input
  }                              #     and take all of them
  [input[1:]]                    # lookup by the 2nd char of flag
  []                             # iterate and output
'

2 aa
3 bb
1 xx

```

Try it online!

# Answer
> 2 votes
# , 84 bytes

```
('cDdu'i.1{[)>@{[:(~.@]((],' ',[)&":"p.;D;~.@D;[-.D=.#~]*1<])1#.=@])@/:~];._1@(LF,])

```

Try it online!

A bit cumbersome, but I've progressively golfed it down from about 100b. I expect more golfing opportunities may be had, but I'm not quite sure where at this point.

## Explanation

This answer can be divided into a bunch of components. Here's an easier to read version of the above (Try it online!) (technically functions *slightly* differently since we're not actually doing `answer_list@sort`, but rather, `(answer_list@/:)~`, which is happens to be the same thing.)

```
get_index =: 'cDdu' i. 1 { [
lines =: ];._1@(LF , ])
sort =: /:~
multi_dup =: #~ ] * 1 < ]
only_once =: [ -. multi_dup
single_dup =: ~.@multi_dup
count_list =: (] , ' ' , [)&":"1 0
counts =: 1 #. =@]
unique =: ~.@]
answer_list =: unique (count_list ; multi_dup ; single_dup ; only_once) counts
uniq_ans =: get_index pick answer_list@sort@lines

```

# Answer
> 1 votes
# Python 2, 115 bytes

```
f,a=input()
f=ord(f[1])%5
for w in sorted(set(a)):C=a.count(w);exec"print'%d '%C*(f>3)+w;"*[C>1,0,C<2,(C>1)*C,1][f]

```

Example:

```
golf % python2.7 uniq.py <<<'["-c",["hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"]]'
4 apple pie
1 dog
2 hello world
1 zebra

```

# Answer
> 1 votes
## Lua, 270 Bytes

Well, that ended being way longer than I though it would, but I'm happy with it.

Takes in a filename via command-line and forms two array while reading it's content (`t={line, repetitions}` and `T={index, line}`). Sorts `T` then outputs via STDOUT depending on the flag.

```
f,m=...io.input(f)t={}T={}for l in io.lines()do
l=l.."\n"t[l]=t[l]and t[l]+1or 1T[#T+1]=t[l]<2 and l or nil
end
table.sort(T)o=""for i=1,#T
do
k=T[i]v=t[k]o=o..(m=="-c"and v.." "..k
or m=="-D"and k:rep(v)or
m=="-d"and v>1 and k
or m=="-u" and v<2 and k or'')end
print(o)

```

### Explanation

```
f,m=...                        -- shorthands for the inputs
io.input(f)                    -- set the file f as the current input stream
t={}                           -- set the array linking a line to its number of occurrence
T={}                           -- set the array containing each line once for sorting purpose
for l in io.lines()            -- iterate over each line in the file
do
    l=l.."\n"                  -- add a newline at the end of it
    t[l]=t[l]                  -- if it's not the first time we see this line
           and t[l]+1          -- increment its number of occurence
         or 1                  -- else set it to 1 occurence
    T[#T+1]=t[l]<2 and l or nil-- and set it in our listing
end
table.sort(T)                  -- sort the list of line
o=""                           -- initialise the output to an empty string
for i=1,#T                     -- iterate over each entry in T
do
    k=T[i]                     -- shorthand for the line's string
    v=t[k]                     -- shorthand for its number of occurence

    -- the following nested ternaries are basically a chained if/elseif
    o=o..                      -- at the end of our current output string
      (m=="-c"                 -- if the flag is -c(ount)
          and v.." "..k        -- add the number of occurrence and the corresponding string
        or m=="-D"             -- if the flag is -D(uplicates)
          and k:rep(v)         -- add v times the line
      or m=="-d" and v>1       -- if the flag is -d(uplicates) and it has appeared >2 times
          and k                -- add this line
      or m=="-u" and v<2       -- if the flag is -u(niq) and it has appeared only once
          and k                -- add this line
        or '')                 -- if neither of these cases are true, had an empty string
end
print(o)                       -- output what we formatted previously :)

```

# Answer
> 1 votes
# Java, 19(import java.util.\*;) + 315 = 334 bytes

```
String f(String[]r,String q){TreeMap<String,Integer>m=new TreeMap();for(String s:r)m.put(s,m.get(s)==null?1:m.get(s)+1);int a=q.charAt(1),v;String o="",k;for(Map.Entry<String,Integer>e:m.entrySet()){v=e.getValue();k=e.getKey()+"\n";while(68==a&&v-->1)o+=k;o+='u'==a&&v<2||'d'==a&&v>1?k:99==a?v+" "+k:"";}return o;}}

```

**Usage**

```
String[] input = {"hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"};
System.out.println("-c");
System.out.println(f(input,"-c"));
System.out.println("-d");
System.out.println(f(input,"-d"));
System.out.println("-D");
System.out.println(f(input,"-D"));
System.out.println("-u");
System.out.println(f(input,"-u"));

```

**Output**

```
-c
4 apple pie
1 dog
2 hello world
1 zebra

-d
apple pie
hello world

-D
apple pie
apple pie
apple pie
hello world

-u
dog
zebra

```

**Explanation** A `TreeMap<String, Integer>` is used to store pairs of words and how many times they were repeated. The TreeMap is sorted so no extra call to sort it is required. Ternary operator is used to construct the output string regarding the input argument.

# Answer
> 1 votes
# Vyxal, 44 bytes

```
⁽R‡'tċ;vh‡'tċ¬;vh≬'tċ;ƛ÷$wẋ;fW‛Ǎ⟇?tḟi$sĊ$†W⁋

```

Try it Online!

A fun little answer that gets to use a list of lambdas. Takes input as `flag`, `list of lines`.

## Explained

```
⁽R‡'tċ;vh‡'tċ¬;vh≬'tċ;ƛ÷$wẋ;fW‛Ǎ⟇?tḟi$sĊ$†W⁋
                             W               # Wrap the stack into a single list:
⁽R                                           # A function that reverses each item in a list
  ‡'tċ;vh                                    # A function that keeps only non-unique items
         ‡'tċ¬;vh                            # A function that keeps only unique items
                 ≬'tċ;ƛ÷$wẋ;f                # A function that repeats non-unique items by their count
                              ‛Ǎ⟇?tḟi        # Get the function at index "cdu".find(input[-1])
                                     $sĊ$†   # Call that function on a list of the counts of each item in the input, sorted alphabetically
                                          W⁋ # Wrap into a single list (needed because of a bug) and join on newlines.

```

# Answer
> 1 votes
# 05AB1E, ~~25~~ 24 bytes

```
C|ÅγøíIÅγ2@ÏIDÅγÏDŠK)ćè»

```

05AB1E doesn't support custom system arguments, so it takes the inputs through STDIN.
The first input-line is the flag, and every other input-line is the input-file.

Try it online or verify all four flags.

**Explanation:**

```
C         # Convert the first (implicit) input-flag from a binary-string to an integer†
|         # Get all other input-lines as a list of strings
 Åγ       # Run-length encode it, and push the list of values and counts separated to
          # the stack
   ø      # Pair the values and lengths together
    í     # Reverse each from [value,count] to [count,value]
I         # Push the list of input-lines again
 Åγ       # Run-length encode it again
   2@     # Check for each count if it's >=2
     Ï    # Only leave the values at the truthy indices
I         # Push the list of input-lines yet again
 D        # Duplicate it
  Åγ      # Run-length encode it a third time
    Ï     # Only leave the values at the truthy (==1) indices
     D    # Duplicate this list of unique items
      Š   # Triple-swap the input,unique,unique lines to unique,input,unique lines
       K  # Remove the unique lines from the input
)         # Wrap the entire stack into a list
 ć        # Extract head; pop list and push remainder-list and first item separately to
          # the stack
  è       # Use that C(input-flag) to 0-based modular index it into the list
   »      # Join each inner list by spaces first (for the list of [count,value] pairs),
          # and then join each string by newlines
          # (after which the result is output implicitly)

```

`C` on strings basically gets the index of each character in the string `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт ΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³\nµ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ•`, and then converts this list of indices to a base-2 integer:

| Flag | `C` | 0-based modular index |
| --- | --- | --- |
| `"-c"` | 252 | 0 |
| `"-d"` | 253 | 1 |
| `"-D"` | 270 | 2 |
| `"-u"` | 227 | 3 |

# Answer
> 0 votes
# Groovy (185 Bytes)

## Golf'd:

```
x={m,l->u=[];u.addAll(l);u.unique();c=u.collect{v->[v,l.count{it==v}]};D=c.collect{a,b->if (b>1){(1..b).collect{a}}};D.remove(null);m=='d'?D.collect{it.unique()}:['D':D,'c':c,'u':u][m]}

```

https://groovyconsole.appspot.com/edit/5173563388592128

## Ungolf'd (Kinda):

```
x = {
    m,l->
        u=[];
        u.addAll(l);
        u.unique();
        c = u.collect {
            v->
                [v, l.count {it==v}]
        }
        D = c.collect {
            a,b->
                if (b>1) {
                    (1..b).collect{a}
                }
        }
        D.remove(null)
        m == 'd' ? D.collect{it.unique()} : ['D':D,'c':c,'u':u][m]
}

```

## Output

* > **u Results** aa bb xx
* > **c Results** \[aa, 3\] \[bb, 2\] \[xx, 1\]
* > **D Results** \[aa, aa, aa\] \[bb, bb\]
* > **d Results** \[aa\] \[bb\]

---
Tags: code-golf
---


title: Generate an RGB colour grid

text:
# Question
Title: Generate an RGB colour grid
This! is an RGB colour grid...

Basically it's a 2-dimensional matrix in which:

* The first row, and the first column, are red.
* The second row, and the second column, are green.
* The third row, and the third column, are blue.

Here are the colours described graphically, using the letters R, G, and B.

Here's how we calculate the colour of each space on the grid is calculated.

* Red + Red = Red (#FF0000)
* Green + Green = Green (#00FF00)
* Blue + Blue = Blue (#0000FF)
* Red + Green = Yellow (#FFFF00)
* Red + Blue = Purple (#FF00FF)
* Green + Blue = Teal (#00FFFF)

# The Challenge

* Write code to generate an RGB colour grid.
* It's code golf, so attempt to do so in the smallest number of bytes.
* Use any programming language or markup language to generate your grid.
* Things I care about:
    + The result should graphically display an RGB grid with the defined colours.
* Things I don't care about:
    + If the output is an image, HTML, SVG or other markup.
    + The size or shape of the colour blocks.
    + Borders, spacing etc between or around the blocks.
    + It definitely doesn't have to have labels telling you what the row and column colours should be.

# Answer
> 36 votes
# Bash, 44

* 2 bytes saved thanks to @NahuelFouilleul
* 2 bytes saved thanks to @manatwork

```
printf "${f=^[[3%dm.}$f$f
" 1 3 5 3 2 6 5 6 4

```

Here, blocks are `.` characters. `^[` is a literal ASCII escape character (0x1b).

You can recreate this script as follows:

```
base64 -d <<< cHJpbnRmICIke2Y9G1szJWRtLn0kZiRmCiIgMSAzIDUgMyAyIDYgNSA2IDQ= > rgbgrid.sh

```

# Answer
> 29 votes
# x86-16 machine code, IBM PC DOS, 43 bytes

```
00000000: be22 01b9 0100 ac8a d83c 10b8 db09 cd10  .".......<......
00000010: b403 cd10 7204 7809 b2ff 42b4 02cd 10eb  ....r.x...B.....
00000020: e2c3 0c0e 1d0e 0a1b 0d0b 91              ...........

```

**Listing:**

```
BE 0122     MOV  SI, OFFSET CT      ; load color bar table into [SI]
        LOOP_COLOR:
B9 0001     MOV  CX, 1              ; display 1 char and clear CH (changed by INT 10H:3)
AC          LODSB                   ; load next color byte
8A D8       MOV  BL, AL             ; move new color to BL
3C 10       CMP  AL, 010H           ; if this is third color in row: SF=0, CF=0
                                    ; else if last color: SF=1, CF=0
                                    ; else continue on same row: CF=1
B8 09DB     MOV  AX, 09DBH          ; AH=9 (write char with attr), AL=0DBH (block char)
CD 10       INT  10H                ; call PC BIOS, display color block
B4 03       MOV  AH, 3              ; get cursor position function
CD 10       INT  10H                ; call PC BIOS, get cursor
72 04       JC   NEXT_COL           ; if not last in row, move to next column
78 09       JS   EXIT               ; if last color, exit
B2 FF       MOV  DL, -1             ; otherwise move to first column and next row
        NEXT_COL:
42          INC  DX                 ; move to next column (and/or row)
B4 02       MOV  AH, 2              ; set cursor position function
CD 10       INT  10H                ; call PC BIOS, set cursor position
EB E2       JMP  LOOP_COLOR         ; loop to next color byte
        EXIT:
C3          RET                     ; return to DOS
        CT  DB   0CH, 0EH, 1DH      ; color table
            DB   0EH, 0AH, 1BH
            DB   0DH, 0BH, 91H

```

This uses the IBM PC BIOS `INT 10H` video services to write the color grid to the screen. Unfortunately the only way to write a specific color attribute requires also writing code to place the cursor in the next correct location, so there's a lot of extra code for that.

Here's the output running on an IBM PC CGA (in 40x25 text mode to make it bigger).

## TL;DR

Here's a more verbose explanation, with more detail of what some of these machine code instructions do.

### Color table

The colors are stored as bytes in the color table (`CTBL`) with the 4-bit color value in the low nibble and a flag value in the high nibble. A `1` in the high nibble signals the end of the row and a `9` signals the end of the list.

This is checked using a single `CMP` instruction which subtracts `0x10` from the color values and sets the result flags. These operands are treated as 8-bit signed values, so the sign flag (positive or negative result) and carry flag (a subtractive borrow was required, meaning the color byte is less than `0x10`) are the interesting ones here. These flags are then checked further down for the conditional logic of whether to advance the row, the column or end the program.

**Examples:**

High nibble `0` means **not** the last in the row and **not** the last in the list:

* `0x0C - 0x10 = 0xFC` -- Result is negative and a carry (borrow) was required

High nibble `1` means it **is** the last color in the row and **not** the last in the list:

* `0x1D - 0x10 = 0x0D` -- Result is positive and no borrow

High nibble `9` means it **is** the last color of the list:

* `0x91 - 0x10 = 0x81` -- Result is negative and no borrow

### Cursor movement

Using the PC BIOS or DOS API for output, the function that allows setting a character color does not automatically advance the cursor, so that has to be done by the program. The cursor position must be fetched each time since the registers are overwritten later by the other functions. The "get" function puts these into the 8-bit registers `DL` for the column, and `DH` for the row. These same registers are what is used by the "set" function to move the cursor to a new location.

We can take advantage of the fact that, on x86 architecture `DH` and `DL` can be manipulated as a single 16-bit register (`DX`). To advance to the next column, we increment `DX` which effectively only increments `DL` (column position). To advance to the next column we would need to instead increment the row number and set the column to `0`. We can do this in only one additional instruction by setting the low nibble (`DL`) to `0xFF` and then continuing the normal program flow incrementing `DX`. Since we're now looking at `DH`/`DL` as a 16-bit value, `DL` becomes `0` and the carry from `0xFF + 1` is added to `DH`.

**Examples:**

Advance to next column:

```
DH   DL   DX
 1    1   0101   ; at row 1, column 1
 1    2   0102   ; add one to DX

```

Advance to next row, first column:

```
DH   DL   DX
 1    2   0102   ; at row 1, column 2
 1   FF   01FF   ; +set DL to 0xFF
 2    0   0200   ; add one to DX

```

# Answer
> 25 votes
# Wolfram Language (Mathematica), 41 bytes

```
Image@Outer[Plus,#,#,1]&@IdentityMatrix@3

```

---

# Wolfram Language (Mathematica), 68 bytes

Mathematica has built-ins for all these colors.

```
Image@{{Red,Yellow,Magenta},{Yellow,Green,Cyan},{Magenta,Cyan,Blue}}

```

# Answer
> 19 votes
# 80386 machine code, IBM PC DOS, 38 bytes

hex:

```
B0 13 CD 10 68 00 A0 1F 66 C7 06 00 00 28 2C 24
00 66 C7 06 40 01 2C 30 34 00 66 C7 06 80 02 24
34 20 00 CD 16 C3

```

asm:

```
mov al,13h
int 10h ; initialize vga 13h mode (320x200x256 colors)
push 0a000h
pop ds ; push video buffer address to ds
mov dword ptr ds:0, 242c28h ; print 3 pixels
mov dword ptr ds:320, 34302ch ; print 3 pixels
mov dword ptr ds:640, 203424h ; print 3 pixels
int 16h ; wait for any keypress
ret ; exit to os

```

scaled output from dosbox:

# Answer
> 19 votes
# Excel VBA (Immediate Window), 80 bytes

```
For i=1To 9:Cells(i Mod 3+1,(i+1)/3).Interior.ColorIndex=Mid(673486857,i,1):Next

```

# Excel VBA (Function), 96 bytes

```
Sub g()
For i=1To 9
Cells(i Mod 3+1,(i+1)/3).Interior.ColorIndex=Mid(673486857,i,1)
Next
End Sub

```

Not a horrible tool for the job... I appreciate the fact that Excel already shows a grid so it is a matter of setting the background color.

Credit to @Neil for suggesting I use `ColorIndex` instead of `Color` leading to a 43 byte savings.

-21 bytes thanks to @Keeta

-16 bytes thanks to @Chronocidal for suggesting the "Immediate Window"

-2 bytes thanks to @i\_saw\_drones

Lots of changes from my original submission :)

# Answer
> 18 votes
# HTML + CSS, ~~121~~ 120 bytes

Worst piece of HTML I've ever wrote. One byte save thanks to @Gust van de Wal

```
b{color:#ff0}a{color:cyan}i{color:lime}u{color:blue
```

```
<pre><body bgcolor=#f0f text=red>█<b>█
█<i>█<a>█
 █<u>█
```

# HTML + CSS, 114 bytes (semi valid)

I'm putting this as semi-valid because the blue is not exactly #0000FF blue and also relies on not having clicked the link.

Thanks to @Lynn for the idea

```
b{color:#ff0}i{color:lime}c{color:cyan
```

```
<pre><body bgcolor=#f0f text=red>█<b>█
█<i>█<c>█
 █<a href=x>█
```

# Answer
> 18 votes
# SVG, ~~210~~ 182 bytes

```
<svg><path d="h3v3h-3" fill=#f0f/><path d="h2v2h-2" fill=#ff0/><path d="m1 1h2v2h-2" fill=#0ff/><line x2=1 stroke=red/><path d="m1 1h1v1h-1" fill=#0f0/><path d="m2 2h1v1" fill=#00f/>

```

Since the size or shape of the colour blocks doesn't matter, quite a few bytes can be golfed off with this slightly odd layout:

# Answer
> 17 votes
# GFA Basic 2.02 (Atari ST), 48 bytes

A manually edited listing in .LST format. Includes many non-printable characters, whose codes are shown within brackets.

```
?"[ESC]c[SOH] [ESC]c[ETX] [ESC]c[ENQ] "[CR]
?"[ESC]c[ETX] [ESC]c[STX] [ESC]c[ACK] "[CR]
?"[ESC]c[ENQ] [ESC]c[ACK] [ESC]c[EOT] "[CR]

```

The operating system of the Atari ST defines extended VT52 commands which are used here.

### Output

The output is a block of \\$24\times24\\$ pixels (9 space characters of \\$8\times8\\$ pixels).

*screenshot from Steem SSE*

# Answer
> 16 votes
# ditaa, 118 bytes

```
/----+----+----\
|cF00|cFF0|cF0F|
+----+----+----+
|cFF0|c0F0|c0FF|
+----+----+----+
|cF0F|c0FF|c00F|
\----+----+----/

```

This is the output using `-E` option:

# Answer
> 15 votes
# R, ~~89~~ ~~50~~ 48 bytes

**Newest version:**

```
image(matrix(c(6,4,5,2:4,1,2),3),col=rainbow(6))

```

Not enough elements in the vector to fill the 3x3 matrix, so it wraps around and reuses the first element.

**Old versions:**

```
image(matrix(c(6,4,5,2:4,1,2,6),3),col=rainbow(6))

image(matrix(c(3,5,6,2,4,5,1:3),3),col=c('red','yellow','magenta','green','cyan','blue'))

```

# Answer
> 15 votes
## Factorio Blueprint String, 705 bytes

I admit, I'm just pushing the limits of what counts as a solution.

```
0eNrdWNGOqyAQ/ReedeNo0daH/ZHNTYOW7ZJFNAi91zT99wua7ZpdaaT1pb40oQ6HOecwA3pGBde0kUwolJ8RK2vRovztjFp2FITb/1TXUJQjpmiFAiRIZUdtzYkMGyIoR5cAMXGg/1AOlz8BokIxxegA0w+6vdBVQaUJuAKQstSV5kTV0qA2dWvm1MKuZ3FecIA6lIf4BV8uwS+YeDKPXzBhPKAkUxjJPAy4AbG5QljZFBEqLOuqYGKa1Vc6YAQzE5Ss+b6gH+TETLQJeWdcUemQ/8Sk0oSPHOgjQkkPqMfT1kEYWzEsI2hpc2gtFtgfO2NkDTMjbIKnCOLv1SrCechJ1UzwSm7zKpksNVN78+xwnffOZKv2s2kS0akPJo4D10FslEd2UDVE9oLn6NU+1i01S/HaKqmkpvNl2DhkSGfJEK1Eha1DhWyWCmvZCzuHCtu7aj5asuQ7ynn99/GqT0f07BjAwXnnx3kohEW7XMPE5+OEs5+EUwdhiL4T0IVh3LNzHlMwfUoB+LTPeK19A2LPkoGbety1f46SUvH4BoLExTHxOCKe3mmIXTJ43ogGp5MlnS47soTR+GeryFyUscex+PzOu65IkPr0OrzW2wFkHn0Ar3c3eN6S4pt63NUH7GvtAn3AafTOo+yf3+jhbDcv9/1XgHz00SBAJ+NNn3uWRJDiDcDWXIf+Aya7oEk=

```

Produced output when placed in-game (low graphics settings used):

To prove that it is a valid solution you need to sample this grid of pixels which do match the specification exactly:

The rest of the image is classified as a border or a spacing which, as said in the question, doesn't matter.

# Answer
> 12 votes
# Perl 6 (and probably similar for many languages) (31 bytes)

```
{'ÿ   ÿÿÿ ÿ ÿÿ  ÿ ÿÿÿ ÿ ÿÿ  ÿ'}   # replace spaces with ASCII 00
                                  # which I can't seem to enter

```

This outputs a headless TIFF file, which used to be generated by Photoshop with the file extension .raw and is presumed to be square unless otherwise specified at the time of opening. Playing around with the color depth (if allowed) could reduce this down further.

# Answer
> 12 votes
# ffplay (ffmpeg), 93 bytes

```
ffplay -f rawvideo -s 3x3 -pix_fmt rgb24 "data:/;base64,/wAA//8A/wD///8AAP8AAP///wD/AP//AAD/"

```

**Old**:

```
ffplay -f lavfi -i testsrc=s=3x3,geq=r=255*not(X*Y):g=255*not((X-1)*(Y-1)):b=255*not((X-2)*(Y-2))

```

# Answer
> 12 votes
# Excel-VBA, ~~89~~ ~~73~~ ~~72~~ 70 bytes

Edit: You can use the immediate window and dispense with the `Sub`/`End Sub` to save 16 bytes:

```
For i=1To 9:[A:C].Cells(i).Interior.ColorIndex=Mid(367648785,i,1):Next

```

Original answer:

```
Sub a()
For i=1To 9
[A1:C3].Cells(i).Interior.ColorIndex=Mid(367648785,i,1)
Next
End Sub

```

This was inspired by Neil's suggestion on this answer, and is my first submission!

Result:

**-2 bytes**: Removal of cell row numbers - thanks to Taylor Scott!

# Answer
> 11 votes
## JavaScript, ~~108~~ 102 bytes

```
console.log(`%c█%c█%c█
`.repeat(3),...[...`320251014`].map(c=>`color:#`+`f0ff00f0`.substr(c,3)))

```

No snippet because this only works in a real browser console and not the snippet's console. Edit: Thanks to @AJFaraday for the screenshot. Explanation: Browsers allow the first parameter of `console.log` to include substitutions. The `%c` substitution takes a parameter and applies it as (sanitised) CSS. Each  block is therefore coloured using the appropriate substring of `f0ff00f0` interpreted as a three-hex-digit colour code.

# Answer
> 10 votes
# HTML/CSS, ~~278~~ ~~141~~ 137 bytes

```
r{color:red}y{color:#ff0}m{color:#f0f}g{color:#0f0}c{color:#0ff}l{color:#00f
```

```
<pre><r>█<y>█<m>█
<y>█<g>█<c>█
<m>█<c>█<l>█
```

*-137 bytes thanks to commenters, most notably @data*
*-4 bytes thanks to @Einacio*

Uses Unicode  (U+2588) for the "blocks", and uses CSS classes/inline style to color them.

I think the `<font>` tags could be golfed more, however changing them to a shorter tag such as `<a>` breaks the `color` attribute

# Answer
> 10 votes
# Octave/MATLAB, ~~57 56~~ 40 bytes

-17 byte thanks to @ExpiredData! Check out their even golfier solution!

```
image(reshape(de2bi(126973007),[3,3,3]))

```

Try it online!

# Answer
> 10 votes
# MATL, ~~44 23 21 20~~ 19 bytes

A direct port of my Octave answer with the suggestions from @ExpiredData and @LuisMendo.

```
126973007Bo7B3*e0YG

```

try it online

# Answer
> 10 votes
\\$\Large{\mathbf{\TeX} \left(\text{MathJax}\right)},~122\\,\text{bytes}\\$

$$ \def\c#1{\color{#1}{\rule{5em}{5em}}} \c{red} \c{yellow} \c{fuchsia} \\ \c{yellow} \c{lime} \c{aqua} \\ \c{fuchsia} \c{aqua} \c{blue} $$

**Golf'd:**

```
$\def\c#1{\color{#1}{\rule{5em}{5em}}}\c{red}\c{yellow}\c{fuchsia}\\\c{yellow}\c{lime}\c{aqua}\\\c{fuchsia}\c{aqua}\c{blue}$

```

**Ungolf'd:**

```
$$
\def\coloredBox#1{\color{#1}{\rule{5em}{5em}}}
\coloredBox{red}
\coloredBox{yellow}
\coloredBox{fuchsia} \\
\coloredBox{yellow}
\coloredBox{lime}
\coloredBox{aqua}    \\
\coloredBox{fuchsia}
\coloredBox{aqua}
\coloredBox{blue}
$$

```

---

**Edits:**

1. Thanks to @flawr for pointing out how to fix the colors!
2. Could shave off \\$14\\,\text{bytes}\\$ by replacing `\rule{5em}{5em}` with , which'd look like$$ \def\d#1{\color{#1}{▉}} \d{red} \d{yellow} \d{fuchsia} \\ \d{yellow} \d{lime} \d{aqua} \\ \d{fuchsia} \d{aqua} \d{blue} $$

, but just doesn't look quite the same.
3. Could probably shave off a few more bytes by finding color names that acceptably resemble the intended colors.
4. Just to show what a decently \\$\mathrm{\TeX}\text{'d}\\$ version of this would look like:$$ {\newcommand{\rotate}\[2\]{{\style{transform-origin: center middle; display: inline-block; transform: rotate(#1deg); padding: 50px}{#2}}}} {\def\place#1#2#3{\smash{\rlap{\hskip{#1em}\raise{#2em}{#3}}}}} {\def\placeBox#1#2#3{\place{#1}{#2}{\color{#3}{\rule{5em}{5em}}}}} {\def\placeLabelTop#1#2#3{\place{#1}{#2}{\large{\textbf{#3}}}}} {\def\placeLabelLeft#1#2#3{\place{#1}{#2}{\rotate{-90}{\large{\textbf{#3}}}}}} \placeLabelTop{1.1}{15.5}{Red} \placeLabelTop{5.5}{15.5}{Green} \placeLabelTop{11.2}{15.5}{Blue} \placeLabelLeft{-6.2}{13.6}{Red} \placeLabelLeft{-7.1}{8.5}{Green} \placeLabelLeft{-6.5}{3.5}{Blue} \placeBox{0}{10}{red} \placeBox{5}{10}{yellow} \placeBox{10}{10}{fuchsia} \placeBox{0}{5}{yellow} \placeBox{5}{5}{lime} \placeBox{10}{5}{aqua} \placeBox{0}{0}{fuchsia} \placeBox{5}{0}{aqua} \placeBox{10}{0}{blue} \place{15.1}{0}{\large{.}} \phantom{\rule{15em}{16.5em}} $$

# Answer
> 10 votes
# Lua + LÖVE/Love2D, ~~186~~ 183 bytes

```
t={[0>1]=0,[0<1]=1}l=love g=l.graphics function l.draw()for i=1,3 do for j=1,3 do g.setColor(t[i<2 or j<2],t[i==2 or j==2],t[i>2 or j>2])g.rectangle('fill',j*10,i*10,10,10)end end end

```

Try it online!

My first code golf entry!

# Answer
> 8 votes
# HTML (GIF), 108 bytes

It's the battle of the web-based image formats! (Any TIF or JPG contenders out there?)

Answer by @A C.

```
<img src=data:image/gif;base64,R0lGODdhAwADAMIGAAAA//8AAP8A/wD/AAD/////AAAAAAAAACwAAAAAAwADAAADBhglNSQEJAA7>
```

---

# HTML (BMP), ~~116~~ 115 bytes

Answer by @ASCII-only.

```
<img src=data:image/bmp;base64,Qk0+AAAAQVNDTxoAAAAMAAAAAwADAAEAGAD/AP///wD/AAAAAAAA//8A/wD//wAAAAAAAP8A////AP8AAAA>
```

---

# HTML (WebP), 116 bytes

Answer by @Hohmannfan.

```
<img src=data:image/webp;base64,UklGRjYAAABXRUJQVlA4TCoAAAAvAoAAAC8gEEjaH3qN+RcQFPk/2vwHH0QCg0I2kuDYvghLcAoX0f/4Hgc>
```

---

# HTML (PNG), ~~151~~ ~~136~~ 135 bytes

-15 bytes thanks to @Hohmannfan.

```
<img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAFElEQVR4AWP4z8Dw/z8DEIIodB4A4D0O8pOGuTgAAAAASUVORK5CYII>
```

---

Also, see my CSS and SVG answers.

# Answer
> 8 votes
# Octave, 38 bytes

```
image(reshape(de2bi(126973007),3,3,3))

```

Try it online!

# Answer
> 7 votes
## Blockly turtle, 45 blocks

Try it online!

How about we play a little game of finding the most ridiculous tool for the job?

Output:

The program (as a screenshot for additional heresy):

Note: The grayed out blocks are also counted towards the metric.

# Answer
> 6 votes
# Node.js, 79 bytes

```
require('fs').writeFile(a='P',a+[...'3331100110101110010011101011001'].join` `)

```

Produces a file named "P" in the PPM format containing the color grid.

# Answer
> 6 votes
# dc (on xterm), 64 bytes

```
Fi16[AP]sF36dD6r31 101dD6rD1[1CP61P[38;5;]Pn[mX]Pz3%0=Fz0<M]dsMx

```

You'll just get a bunch of wacky escape codes instead of colors, but you can still try it online!

By my understanding, the 16 basic ANSI colors are free to be interpreted however the terminal wants. On the other hand, the 216 colors in the xterm color cube have explicit RGB values. I am using these codes and printing a grid of `X`s:

First we set the input radix to base 15 with `Fi`. This costs two bytes, but gives back three, so... a net gain of a byte (and a big ol' loss in readability). Next we're trying to get our color values onto the stack. In decimal, this would be `21 51 201 51 46 226 201 226 196`, but we're in wacky mode so it's going to be `16 36 D6 36 31 101 D6 101 D1`. We eliminate one of the spaces by slotting in a macro we need to define at some point, `[AP]sF` (which simply prints a line feed). We can shrink `36 D6 36` and `101 D6 101` by placing the first value on the stack, duplicating it, placing the second, and then swapping (`36dD6r`, `101dD6r`).

Macro `M` handles the printing and whatnot. `1CP` prints the escape character. Brackets are used to delimit strings, and as far as I know are not escapable, so we need to print the bracket with an ASCII value as well, `61P`. `[38;5;]P` is the 'set foreground color from the numbered list' code. `n` prints the value from the top of the stack w/o a newline, popping it. `[mX]P` ends the code and prints an 'X'. `z3%0=F` checks the stack depth mod 3, running our line feed macro `F` when necessary. `z0<M` keeps `M` running as long as there's stuff on the stack. `dsMx` to run.

Note that if you run this in dc in an xterm, it'll leave your foreground color blue. `1CP61P74P` (input shown in the screenshot) should reset this.

# Answer
> 5 votes
## C#, ~~248~~ ~~204~~ 198 bytes

```
class P{static void Main(){for(int i=0;i<12;i++){foreach(dynamic n in Enum.GetValues(typeof(ConsoleColor)))if((""+n)[0]=="RYMRYGCRMCBR"[i])Console.BackgroundColor=n;Console.Write(i%4<3?" ":"\n");}}}

```

Output:

# Answer
> 5 votes
# TI-Basic, x bytes (will score when I can)

Note: content filter is blocking me from looking up the token sizes for each of these commands. If anyone wants to score for me, go for it.

```
TextColor(11
Text(0,0,"0"
TextColor(19
Text(0,2,"0"
Text(2,0,"0"
TextColor(13
Text(4,0,"0"
Text(0,4,"0"
TextColor(14
Text(2,2,"0"
TextColor(18
Text(2,4,"0"
Text(4,2,"0"
TextColor(17
Text(4,4,"0"

```

This look really bad on my little calculator screen. But hey, shape doesn't matter :^)
Golf output:
Modified for 8x larger output:

# TI-BASIC, x bytes

Using Pxl-On instead of Text:

```
Pxl-On(0,0,11
Pxl-On(0,1,19
Pxl-On(0,2,13
Pxl-On(1,0,19
Pxl-On(1,1,14
Pxl-On(1,2,18
Pxl-On(2,0,13
Pxl-On(2,1,18
Pxl-On(2,2,17

```

Output:
Blown up ~11x:

# Answer
> 4 votes
# Jelly, 16 bytes

```
“IỤỵ7ỤĖm8’b4K”P;

```

Try it online!

Niladic link or full program that produces a portable pixmap format image of the desired grid.

# Answer
> 4 votes
## C++, SFML, 177 bytes

```
#include<SFML/Graphics.hpp>
int d[]={255,65535,0xFF00FF,65535,65280,0xFFFF00,0xFF00FF,0xFFFF00,0xFF0000};void f(){sf::Image g;g.create(3,3,(sf::Uint8*)d);g.saveToFile("a.jpg");}

```

Uses `sf::Image::create(int,int,unsigned char*)` method to create an image with rgb values in it

# Answer
> 4 votes
# PostScript, 195 bytes

Output look closer:

```
%!PS
/r{rlineto}def/s{newpath moveto 0 1 r 1 0 r 0 -1 r closepath setrgbcolor fill}def
1 0 0 0 2 s
1 1 0 1 2 s
1 0 1 2 2 s
1 1 0 0 1 s
0 1 0 1 1 s
0 1 1 2 1 s
1 0 1 0 0 s
0 1 1 1 0 s
0 0 1 2 0 s

```

To test just paste the code in a blank file and save as `something.ps` and open in a pdf viewer.

To enlarge the output add `50 50 scale` (or some other number) on the second line of the file.

# Answer
> 4 votes
# \[x86 Assembly\], 42 bytes

```
org 100h
   mov al,13h
   int 10h
   push 40960
   pop es
   xor di,di
   mov bp,8
L: mov eax,[C+bp]
   stosd
   add di,316
   sub bp,4
jnc L

ret
C: dd 00203424h, 0034302ch, 00242c28h

```

Dump:

```
00000000  B013              mov al,0x13
00000002  CD10              int 0x10
00000004  6800A0            push word 0xa000
00000007  07                pop es
00000008  31FF              xor di,di
0000000A  BD0800            mov bp,0x8
0000000D  668B861E01        mov eax,[bp+0x11e]
00000012  66AB              stosd
00000014  81C73C01          add di,0x13c
00000018  83ED04            sub bp,byte +0x4
0000001B  73F0              jnc 0xd
0000001D  C3                ret
0000001E  0024              add [si],ah
00000020  3420              xor al,0x20
00000022  002C              add [si],ch
00000024  3034              xor [si],dh
00000026  0028              add [bx+si],ch
00000028  2C24              sub al,0x24

```

# Answer
> 4 votes
## BASIC C64, 106 bytes

```
0 POKE53281,0
1 DATA144,28,158,156,144,13,158,30,159,144,13,156,159,31,144
2 READA:PRINTCHR$(A)+"o";:GOTO2

```

# Answer
> 4 votes
## Processing 3: 191 178 161 Bytes

```
int l=0;void setup(){size(33,33);}void draw(){int i=l%33;int j=l/33;stroke((i%3==0||j%3==0)?255:0,(i%3==1||j%3==1)?255:0,(i%3==2||j%3==2)?255:0);point(i,j);l++;}

```

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

```
Grid@Partition[RGBColor/@Unitize[Total/@Tuples[IdentityMatrix@3,{2}]],3]

```

# Answer
> 3 votes
# CSS, ~~147~~ 138 bytes

Uses the `box-shadow` and `background` properties.

```
html{width:1em;height:1em;background:#f0f;box-shadow:red 0 1em,#ff0 1em 1em,#ff0 0 2em,#0f0 1em 2em,#0ff 2em 2em,#0ff 1em 3em,#00f 2em 3em
```

*-9 bytes (Gust van de Wal):* Make background magenta to cover for two pixels instead of one.

# Answer
> 3 votes
## CSS, ~~157~~ ~~155~~ ~~147~~ 139 bytes

```
html{height:100%;background-blend-mode:screen;--:red 33%,#0f0 0 67%,blue 0;background:linear-gradient(90deg,var(--)),linear-gradient(var(--
```

Unlike @darrylyeo's answer no zooming is required (or possible!) I just wanted to show off `background-blend-mode`, despite it being far too long a keyword for code golf. Edit: Saved ~~2~~ 10 bytes with help from @GustvandeWal. Saved a further 8 bytes thanks to @darrylyeo.

# Answer
> 3 votes
## APL (dzaima/APL), ~~186~~ 161 bytes

Uses dzaima's Processing integration.

```
G←P5.G
P5.draw←{p←G.pt
G.stroke←'00f'
p 3 3
G.stroke←'0ff'
p 2 3 3 2
G.stroke←'f0f'
p 1 3 3 1
G.stroke←'0f0'
p 2 2
G.stroke←'ff0'
p 1 2 2 1
G.stroke←'f00'
p 1 1}

```

-25 bytes after applying some of dzaima's suggestions and 3 character color codes.

### Grid (Heavily Magnified):

### Actual size:

# Answer
> 2 votes
# Raw PPM image, 36 bytes

```
$ xxd image.ppm
00000000: 5036 2033 2033 2031 0a01 0000 0101 0001  P6 3 3 1........
00000010: 0001 0101 0000 0100 0001 0101 0001 0001  ................
00000020: 0100 0001

```

It might not fit the requirements, but it's fun to include anyway as a benchmark.

# Answer
> 2 votes
# Python 2, 74 48 47 bytes

```
print('\033[9%sm#'*3+'\n')*3%tuple('135326564')

```

Depends on system colors (this assumes 'bright' colors are pure RGB values), but works by modifying the foreground color of `#`s in the terminal.

-26 bytes thanks to xnor

-5 bytes by realizing the color blocks don't need to be rectangles, +4 bytes from miscounting

# Answer
> 2 votes
**Python Turtle, 202 bytes, inspired by Aaron F's answer**

```
import turtle as m
t=m.Turtle()
t.shape("square")
l=t.left
i=0
y=["#ff0","#f0f","cyan"]
for c in["red"]+y+["#0f0"]+y:t.color(c);t.stamp();a={2:270,5:90}.get(i,0);l(a);t.fd(21);l(a);i+=1
t.color("blue")

```

# Answer
> 2 votes
# x86 machine code, 16-bit, MS-DOS, EGA display, ~~40~~ 39 bytes

Hexdump:

```
68 80 b8 07 31 ff be 1e 01 b9 09 00 2e 8a 24 46
b0 db d0 ec ab 73 04 81 c7 9a 00 e2 ef c3 18 1c
1b 1c 14 17 1a 16 02

```

Execution log:

It writes the "bar" character  with various attributes to display memory, starting from address `b8800` (display memory starts at `b8000`; I added an offset to move the output to a better place on the screen).

I could use the fact that display memory is filled with space characters, and change their background instead of overwriting them with the bar character, but for best match I needed bright colours, and they are not supported as background.

I developed the code using `debug.com` in a DOS emulator here. Source code:

```
; the following should read "push b880" but debug.com cannot emit this instruction
db 68, 80, b8
pop es
xor di, di
mov si, 11e
mov cx, 9
; 10c (loop target)
cs:
mov ah, [si]
inc si
mov al, db
shr ah, 1
stosw
jnc 11b
add di, 9a
; 11b (jump target)
loop 10c
ret
db 18, 1c, 1b, 1c, 14, 17, 1a, 16, 02

```

# Answer
> 2 votes
# GeoGebra Script, 157 bytes

```
Execute[Flatten[Sequence[Sequence[{"P"+i+j+"=("+j*.2+","+i*.2+")","SetColor[P"+i+j+","+(i==2∨j==0)+","+(i==1∨j==1)+","+(i==0∨j==2)+"]"},i,0,2],j,0,2]]]

```

Try it online!

Output:

# Answer
> 2 votes
# Python 123 bytes

```
from matplotlib.pyplot import*;r=0,1,2;imshow([[[2.if i==j==k else 1if(i==k)|(j==k)else 0for k in r]for j in r]for i in r])

```

Seeing no one took advantage of matplotlib in a graphical-output challenge I figured it had to be done for completion.

## Explanation

We can take advantage of the fact that matplotlib will autolevel our colors if we give it floating point data instead of integer data. This means we don't have to worry about specifying specific color values, just the correct ratios. So a red pixel we can define as (2, 0 ,0) and a yellow pixel we can define as (1, 1, 0). All we have to do is make sure at least one of these elements is a float, and matplotlib will automatically scale it to the proper 255-bit color for us.

Ungolfed code for clarity.

```
from matplotlib.pyplot import *
r = (0, 1, 2)
image = [[[0 for i in r] for i in r] for i in r]
for i in r:
    for j in r:
        for k in r:
            if i==j==k: #matching pixel for diagonal element
                image[i][j][k] = 2.
            elif i==k or j==k: #matching pixel for partial component
                image[i][j][k] = 1
imshow(image)

```

# Answer
> 2 votes
# Java 10, 229 bytes

```
import java.awt.*;v->new Frame(){{add(new Panel(){public void paint(Graphics g){var G=(Graphics2D)g;for(int i=9;i-->0;G.fillRect(i%3*4,i/3*4,4,4))G.setColor(new Color(i<4|i==6?255:0,i%2>0|i==4?255:0,i>4|i==2?255:0));}});show();}}

```

Screenshot of the actual 12x12 pixels result:

Screenshot of the 10 times larger 120x120 pixels result (the `4` in the `fillRect` are replaced with `40`):

**Explanation:**

```
import java.awt.*;                // Required import for almost everything
v->                               // Method with empty unused parameter and Frame return
  new Frame(){                    //  Create the Frame
   {                              //   In an inner code-block:
     add(new Panel(){             //    Add a Panel we can draw on:
       public void paint(Graphics g){
                                  //     Overwrite its paint method:
         for(int i=9;i-->0        //      Loop `i` in the range (9,0]:
             ;                    //        After every iteration:
              G.fillRect(i%3*4,i/3*4,4,4))
                                  //         Draw a 4x4 pixel rectangle at coordinate
                                  //         x=i%3*4, y=i//3*4
           G.setColor(new Color(  //       Set the current RGB color to:
             i<4|i==6?255:0,      //        Red: 255 if `i` is 0,1,2,3,6; 0 otherwise
             i%2>0|i==4?255:0,    //        Green: 255 if `i` is 1,3,4,5,7; 0 otherwise
             i>4|i==2?255:0));}});//        Blue: 255 if `i` is 2,5,6,7,8; 0 otherwise
     show();}}                    //    And show the Frame when we're done

```

# Answer
> 2 votes
# Ruby, 113 bytes (Ubuntu Terminal)

```
a=[[91,93,95],[93,32,96],[95,96,34]]
for b,c,d in a do puts"\e[#{b}m█\e[0m\e[#{c}m█\e[0m\e[#{d}m█\e[0m" end

```

In Terminal.app, the colors do not display properly:

According to Wikipedia, this program should fit the spec if it's run on Ubuntu, which is the only terminal which has the colors as per specifications. Can someone help me out with this?

Try it online!

# Answer
> 1 votes
# HTML, 150 bytes

```
<table bgcolor=#0ff><td bgcolor=red><td bgcolor=#ff0><td bgcolor=#f0f><tr><td bgcolor=#ff0><td bgcolor=#0f0><tr><td bgcolor=#f0f><td><td bgcolor=#00f>
```

---

# HTML, 151 bytes

```
<table bgcolor=#0ff><td bgcolor=#f00><td bgcolor=#ff0><td bgcolor=#f0f><tr><td bgcolor=#ff0><td bgcolor=#0f0><tr><td bgcolor=#f0f><td><td bgcolor=#00f>
```

# Answer
> 1 votes
# Python 2, 216 bytes

```
l=[41,43,45,43,42,46,45,46,44]
print(''.join(['\033[0;37;'+`l[i+j*3]`+'m \033[0m'+'\n'*(j==2)for i in range(3)for j in range(3)]))

```

Unfortunately, this code does not work well with TIO, but here is a link regardless: Try it online!

# Answer
> 1 votes
## Javascript, ~~134~~ ~~131~~ 111 bytes

```
for(n=0,i=12;--i;)document.write(i%4?'<font color=#'+'f00ff0f0fff00f00fff0f0ff00f'.substr(n++*3,3)+'>█':'<br>')
```

# Answer
> 1 votes
I don't know if this is allowed. `turtle` is a built-in, but it relies on TK, which might not always be available (eg. TIO doesn't like this).

Anyway, it was fun to do. Tried to get it as small as possible while still using Turtle. (269 bytes because those spaces aren't spaces, they're tabs!)

## Python 2 or 3, 269 bytes

```
import turtle
t=turtle.Turtle()
t.shape("square")
l=t.left
i=0
y=["yellow","magenta","cyan"]
for c in ["red"]+y+["green"]+y+["blue"]:
    i+=1
    t.color(c)
    t.stamp()
    if i==9:
        break
    elif i%3==0:
        a=90 if i==6 else 270
    else:
        t.fd(21)
        continue
    l(a)
    t.fd(21)
    l(a)

```

# Answer
> 1 votes
# Pyth, 25 bytes

```
.wm.eXbk;mX*3]Zd=k255G=G3

```

The online interpreter doesn't show generated images, so this program must be run locally. It generates a 3x3 pixel image like the one in the question.

# Answer
> 1 votes
# SVG, 212 bytes

Uses the CSS property `mix-blend-mode: lighten`.

```
<svg><g fill=red><path d="M0 0h3v1H0z"/><path d="M0 0h1v3H0z"/><g fill=lime><path d="M0 1h3v1H0z"/><path d="M1 0h1v3H1z"/><g fill=blue><path d="M0 2h3v1H0z"/><path d="M2 0h1v3H2z"/><style>*{mix-blend-mode:lighten
```

---

# SVG, ~~276~~ 240 bytes

Previous answer using `<rect>` instead of `<path>`.

```
<svg><g fill=red><rect width=3 height=1 /><rect width=1 height=3 /><g fill=lime><rect width=3 height=1 y=1 /><rect width=1 height=3 x=1 /><g fill=blue><rect width=3 height=1 y=2 /><rect width=1 height=3 x=2 /><style>*{mix-blend-mode:lighten
```

# Answer
> 1 votes
# Processing, ~~225~~ 210 chars/bytes

Exhilarating code, I know.

```
fill(#FF0000);
rect(0,0,4,4);
fill(#FFFF00);
rect(0,4,4,4);
rect(4,0,4,4);
fill(#FF00FF);
rect(0,8,4,4);
rect(8,0,4,4);
fill(#00FF00);
rect(4,4,4,4);
fill(#00FFFF);
rect(4,8,4,4);
rect(8,4,4,4);
fill(#0000FF);
rect(8,8,4,4);

```

# Answer
> 1 votes
# Ruby with Shoes, 89 characters

```
Shoes.app{n=0..2
n.map{|i|n.map{|j|fill n.map{|e|i==e||j==e ?:F:0}*''
rect i*9,j*9,9,9}}}

```

Sample output:

# Answer
> 1 votes
# \[C64 Assembly\], 58 bytes

Machine code:

```
01 08 0b 08 e3 07 9e 32 30 35 39 20 a2 03 ca
a9 a0 9d 20 04 9d 28 04 9d 50 04 bd 30 08 9d
20 d8 bd 33 08 9d 28 d8 bd 36 08 9d 50 d8 d0
e0 4c 2d 08 02 07 04 07 05 03 04 03 06

```

Assembly code:

```
*=$0801
    .word (+), 2019     ;line number
    .null $9e, ^+       ;sys <start>
+
    ldx #$03
    loop:
        dex
        lda #$a0
        sta $0400,x
        sta $0428,x
        sta $0450,x

        lda tabcol+0,x
        sta $d800,x
        lda tabcol+3,x
        sta $d828,x
        lda tabcol+6,x
        sta $d850,x
    bne loop
    jmp *

tabcol:
.byte $02,$07,$04,$07,$05,$03,$04,$03,$06

```

# Answer
> 1 votes
# PostScript, ~~77~~ ~~61~~ 60 bytes

Code:

```
3 3 1[.1 0 0 .1 0 0]<AC80C9809A8>false 3 colorimage showpage

```

Result:

# Answer
> 1 votes
# Racket (BSL + 2htdp/image), 152 bytes

```
(define(s q)(star 9 'solid q))(above(beside(s 'red)(s 'yellow)(s 'magenta))(beside(s 'yellow)(s 'green)(s 'cyan))(beside(s 'magenta)(s 'cyan)(s 'blue)))

```

Ungolfed:

```
(define (s q) (star 9 'solid q))
(above
 (beside (s 'red) (s 'yellow) (s 'magenta))
 (beside (s 'yellow) (s 'green) (s 'cyan))
 (beside (s 'magenta) (s 'cyan) (s 'blue)))

```

`star` was the shortest shape. Overall a pretty boring answer. I'll try to come up with a more interesting one when time permits.

# Answer
> 1 votes
# Tcl/Tk, 208 bytes

```
gri [can .c]
proc O {x y z w C\ #FF0} {.c cr o $x $y $z $w -f $C}
O 2 2 5 5 red
O 8 2 11 5
O 14 2 17 5 #F0F
O 2 8 5 11
O 8 8 11 11 #0F0
O 14 8 17 11 #0FF
O 2 14 5 17 #F0F
O 8 14 11 17 #0FF
O 14 14 17 17 #00F

```

Notes:

* There is an Enter on bottom
* Ran in interactive shell to have commands' abbreviations enabled by default.

# Answer
> 0 votes
# JavaScript + HTML Canvas, 153 bytes

```
c=c.getContext`2d`;for(i=0;i<9;i++){x=i/3|0;y=i%3;c.fillStyle=`rgb(${(!x|!y)*255},${(x==1|y==1)*255},${(x>1|y>1)*255})`;c.fillRect(x,y,1,1)}
```

```
<canvas id=c>
```

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


# Question
Title: Detect the Nearly Perfect Licence Plates
***Note:** This is inspired by this question by **@Willbeing** where task was to count the number of perfect plates of a certain length, but it's slightly different.*

---

We call ***a perfect licence plate*** that plate whose text satisfies the following conditions:

* It consists of characters, which can either be uppercase letters(`[A-Z]`) or digits(`[0-9]`)
* Summing the positions of its letters in the English alphabet, ***1-indexed*** (i.e: `A=1,B=2,...,Z=26`) gives an integer **n**
* Getting each chunk of digits, summing them and then multiplying all the results gives the same result, **n**
* **n** is a perfect square (e.g: `49` *(72)*, `16` *(42)*)

A **nearly perfect licence plate** meets the conditions for a perfect licence plate, except that **n** is *not* a perfect square.

---

# Input

A string representing the text of the licence plate, taken as input in any standard form, except for hardcoding.

# Output

If the given string represents a ***nearly perfect*** licence plate, return a truthy value (e.g: `True` / `1`), otherwise return a falsy value (e.g: `False` / `0`). Any standard form of output is accepted while taking note that this loopholes are strictly forbidden.

---

### Examples

```
licence plate -> output

A1B2C3 -> 1

A + B + C = 1 + 2 + 3 = 6
1 * 2 * 3 = 6
6 is not a perfect square, 6 = 6 => nearly perfect plate

01G61 -> 1

(0 + 1) * (6 + 1) = 7
G = 7
7 is not a perfect square, 7 = 7 => nearly perfect plate

11BB2 -> 0

(1 + 1) * 2 = 4
B + B = 2 + 2 = 4
4 = 4, but 4 is the square of 2 => perfect license plate (not what we want)

67FF1 -> 0

(6 + 7) * 1 = 13
F + F = 6 + 6 = 12
12 != 13 => not perfect at all!

```

---

## Scoring

This is , so the shortest answer in bytes wins!

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

+1 byte to fix a bug spotted by ChristianSievers (incorrectly dealing with substrings of only zeros) +1 byte to fix false positives for `"0"`, `"00"`, ... found during above fixing (0 is a perfect square).

```
i@€ØAS;Æ²$
e€ØAœpV€€LÐfS€P;0⁼Ç

```

**Try it online!**, or run tests

### How?

```
i@€ØAS;Æ²$ - Link 1: [letter-sum, letter-sum is perfect square?]: plate
i@€        - index of €ach char in plate [reversed @rguments] (1-based, 0 otherwise) in:
   ØA      -     uppercase alphabet
     S     - sum
         $ - last two links as a monad:
      ;    -     concatenate with:
       Æ²  -         is square?

e€ØAœpV€€LÐfS€P;0⁼Ç - Main link: plate                        e.g. "11BB2"
    œp              - partition plate at truthy values of:
e€                  -     is in? for €ach char in plate:
  ØA                -         uppercase alphabet                   [['1','1'],[''],['2']]
      V€€           - evaluate for €ach for €ach                   [[1,1],[],[2]]
          Ðf        - filter keep:
         L          -     length                                   [[1,1],[2]]
            S€      - sum each                                     [2,2]
              P     - product                                      4
               ;0   - concatenate a zero                           [4,0]
                  Ç - last link (1) as a monad (taking plate)      [4,1]
                 ⁼  - equal? (non-vectorising)                     0

```
> 7 votes

# Answer
# MATL, ~~36~~ ~~34~~ ~~33~~ 35 bytes

```
3Y432YXU"@V!Usvp]GlY2&msy=wtQ:qUm~v

```

Try it at **MATL Online**

**Explanation**

```
        % Implicitly grab input as a string
3Y4     % Push the predefined literal '[A-Za-z]+' to the stack
32      % Push the literal 32 to the stack (ASCII for ' ')
YX      % Replace the matched regex with spaces (puts a space in place of all letters)
U       % Convert the string to a number. The spaces make it such that each group of
        % of consecutive digits is made into a number
"       % For each of these numbers
  @V!U  % Break it into digits
  s     % Sum the digits
  v     % Vertically concatenate the entire stack
  p     % Compute the product of this vector
]       % End of for loop
G       % Explicitly grab the input again
lY2     % Push the predefined literal 'ABCD....XYZ' to the stack
&m      % Check membership of each character in the input in this array and
        % return an array that is 0 where it wasn't a letter and the index in 'ABC..XYZ'
        % when it was a letter
s       % Sum the resulting vector
y       % Duplicate the product of the sums of digits result
=       % Compare to the sum of letter indices result
w       % Flip the top two stack elements
Q       % Add one to this value (N)
t:      % Duplicate and compute the array [1...N]
q       % Subtract 1 from this array to yield [0...N-1]
U       % Square all elements to create all perfect squares between 1 and N^2
m~      % Check to ensure that N is not in the array of perfect squares
v       % Vertically concatenate the stack.
        % Implicitly display the truthy/falsey result

```
> 7 votes

# Answer
# Python 2, ~~120~~ 118 bytes

```
s=t=p=0;r=1
for n in input():
 h=int(n,36)
 if h>9:s+=h-9;r*=t**p
 p=h<10;t=(t+h)*p
print(s==r*t**p)&(int(s**.5)**2<s)

```

Try it online!

Interprets each character as a number in base-36 (`h`). Converts to decimal and adds to the sum if `h>9` (meaning it's a letter), otherwise adds to a variable which gets multiplied to form the running product later.
> 6 votes

# Answer
# Python 2, ~~267~~ 207 bytes

 Saved 60 bytes thanks to ovs

```
import re
def g(l):a=reduce(lambda a,b:a*b,[sum(map(int,list(i)))for i in re.sub(r'\D',' ',l).split()],1);return a==sum(sum(k)for k in[[ord(i)-64for i in x]for x in re.sub(r'\d',' ',l).split()])and a**.5%1>0

```

Function with usage: `print(g('A1B2C3'))`

Try it online!
> 4 votes

# Answer
# Python 3, ~~163 156 155 164~~ 161 bytes

```
from math import*
m=1;s=t=p=0
for x in input():
 try:t+=int(x);p=1
 except:m*=[1,t][p];p=t=0;s+=ord(x.upper())-64
if p:m*=t
print(m==s and sqrt(m)!=int(sqrt(m)))

```

Try it online!

* saved 7 bytes thanks to Jonathan and Shooqie
* saved 1 byte: Also Fixed the false positive issue. Thanks to Jonathan for pointing it out!
* added 11 bytes: Previous edit was wrong(the multiplication of sum of digit was going on in an unwanted loop)
> 4 votes

# Answer
# Perl 5, 80 bytes

79 bytes of code + `-p` flag.

```
$.*=eval s/./+$&/gr for/\d+/g;$t-=64-ord for/\pl/g;$_=$.==$t&&($.**.5|0)**2!=$.

```

Try it online!

`$.*=eval s/./+$&/gr for/\d+/g;` multiplies the sums of consecutive digits. (I'm using `$.` because it's initial value is `1`, which mean it's the neutral element for multiplication). More precisely, for each chunk of digits (`for/\d+/g`), `s/./+$&/gr` places a `+` before each digit, then the string is `eval`uated, and multiplied with the current product.
Secondly, `$t-=64-ord for/\pl/g;` sums in `$t` each letter (`for/\pl/g`). (`ord` return the ascii code for the letter, and `64-..` makes it be between 1 and 26.
Finally, `$.==$t` checks that both values are the same, and `($.**.5|0)**2!=$.` that it's nor a perfect square.
> 4 votes

# Answer
# Retina, 143 bytes

Returns 1 for true, 0 for false

```
[1-9]
$*
10|01
1
S_`(\D)
O`
{`1(?=1*\n(1+))
$1
)2=`1+\n

[J-S]
1$+
[T-Z]
2$+
T`0L`ddd
1>`\d+\n?
$*
^((?(1)((?(2)\2(11)|111))|1))*\n

^(1*)\n\1$

```

Try it Online!

**Explanation:**

```
[1-9]
$*
10|01
1

```

First, we replace all non-zero digits with their unary representation. We remove any zeroes with an adjacent digit so that they don't affect our unary operations

```
S_`(\D)

```

Split the resulting string on letters, being careful to exclude empty lines (this is a problem when two letters are consecutive `AA`).

```
O`
{`1(?=1*\n(1+))
$1
)2=`1+\n

```

Sort the string lexicographically. Then repeatedly do the following:

1) Replace each `1` with the number of `1`s on the following line (this mimics multiplication)

2) Remove the second line of `1`s

```
[J-S]
1$+
[T-Z]
2$+
T`0L`ddd

```

Replace letters `J-S` with `1J`, `1K`, etc. and replace letters `T-Z` with `2T`, `2U`, etc. Then, replace each of the groups `A-I`, `J-S`, and `T-Z` with `1-9`. We will be left with the numerical value of each letter (eg. `13` for `M`).

```
1>`\d+\n?
$*

```

Convert every line but the first into unary (the first line is already in unary). Concatenate these lines. We are now left with a string of the form `<product of digits>\n<sum of letters>`.

```
^((?(1)((?(2)\2(11)|111))|1))*\n

```

Replace a square number with the empty string. This uses the "difference tree" method.

```
^(1*)\n\1$

```

Return `1` if the two strings on either side of the `\n` match. Otherwise, return `0`.
> 3 votes

# Answer
# Ruby, 87 bytes

```
->s{m=0
n=1
s.scan(/(\d+)|./){$1?n*=$1.bytes.sum{_1-48}:m+=$&.ord-64}
m==n&&m**0.5%1>0}

```

Attempt This Online!
> 1 votes

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