title: Help! My calculator malfunctions!

text:
# Question
Title: Help! My calculator malfunctions!
## Introduction

My calculator is behaving weird. Sometimes when I type in an `8` it displays a `2`. And sometimes when I type in a `6` it displays a `+`. Some buttons are mixed up!
Could anyone help me determine which?

## Challenge:

**Input:** List of *incorrect* equations, with *correct* results.

**Output:** The two buttons that are swapped.

**For example:**
An input could be:

```
123    = 3
8423   = 252
4+4    = 8
4*7-10 = 417
9/3    = 3
42-9   = -36

```

For which the expected outputs are: `2` and `*`.

Why? Because ALL the equations would be correct if we swap the 2's and \*'s:

```
1*3    = 3
84*3   = 252
4+4    = 8
427-10 = 417
9/3    = 3
4*-9   = -36

```

## Challenge rules:

* Input can be in any reasonable format. Can be a single string with space delimited; a string-list or -array; a list with equations and another list with the correct results. Your call. Please state which input format you've used!
NOTE: This also means you are allowed to input the test case `-5--15` as `-5- -15` or `-5 - -15`. However, a number resulting in `--` should either be inputted without spaces or with a space between every digit. So test case `9119` can be inputted like `9119` or `9 1 1 9` (reason `91 19` isn't allowed is because you can then be guided by the space for finding `- -`). So spaces are (somewhat) optional and allowed.
* Output format can be in any reasonable format as well. Can be two characters; a single two-character string; a string-list containing the two characters. Your call. Again, please state which output format you've used!
* You are allowed to use any distinct 14 outputs that map to `0123456789+-*/`. So you are even allowed to output two distinct integers if you want to (again, please specify the mapping you've used, if any).
* You only have to support integers. So there won't be any test cases like `1/8=0.125` or `1/8=0`.
* Arithmetic operands you'll have to support: addition (`+`); subtraction (`-`); multiplication (`*` or `×` or `·`); division (`/` or `÷`). (NOTE: Characters between parenthesis are only added as clarification.)
* You'll have to support negative numbers. This means `-` can be interpreted in the equation as both a mathematical operand or a negative indicator.
* You can assume the given incorrect equations and supposed correct equations are always valid (so there won't be things like `4-/2` or `9+-+8` for example).
* The incorrect input-equations can contain a division by 0, but the corrected and expected equations will never contain division by 0.
* The incorrect input-equations can already be correct even if you swap the intended buttons back.
* A given input equation can be irrelevant for the buttons to swap (like the `4+4=8` and `9/3=3` equations, with the swapped buttons `2` and `*`).
* You can assume there will always be only one possible swap that can be made with the given test cases.
* Both buttons to swap will always be present in at least one of the incorrect equations.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases:

```
Input:
123    = 3
8423   = 252
4+4    = 8
4*7-10 = 417
9/3    = 3
42-9   = -36

Output: 2 *

Input:
4/2   = 6
3/0   = 3
0/8+2 = 4
95-5  = 90
4+2   = 2

Output: + /

Input:
7+4    = 11
5-15   = 46
212-23 = -2121

Output: 1 -

Input:
4+8/2-9*1 = -5
99/3-13   = 20
1+2+3+4   = 10
4-3-2-1   = -6

Output: 2 4

Input:
18/18  = 1
98-8   = 90
55*88  = 4840
-5--15 = 10

Ouput: 5 8

Input:
9119    = 18
5-3     = 513
8*-9    = 152
13116/3 = -1

Output: 1 -

```

# Answer
> 5 votes
# Perl 6, ~~132~~ 113 bytes

*Thanks to Jo King for -19 bytes.*

```
->\e,$r {first {($!=e.trans($_=>.flip))ne e&&try "all {$!.&{S:g/\-/- /}} Z==$r".EVAL},[X~] (|^10,|<+ - * />)xx 2}

```

Try it online!

Input is a comma-separated string of equations and a comma-separated string of results (hope this is OK). Output is a string containing the two swapped buttons.

Correctly handles `--`. Might product false positives for `---`, `++`, `**`, or `//`, but I couldn't come up with a test case.

# Answer
> 11 votes
# JavaScript (ES7), ~~159~~ 158 bytes

*Edit: new version to comply with the updated rules regarding `--`*
*Saved 1 byte thanks to @Shaggy*

Takes input in currying syntax `(e)(r)` where ***e*** is the array of equations and ***r*** is the array of expected results. Returns an array of characters.

```
e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))

```

### Test cases

```
let f =

e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))

console.log(JSON.stringify(f
  ([ '123', '8423', '4+4', '4*7-10', '9/3', '42-9' ])
  ([ 3, 252, 8, 417, 3, -36 ])
));

console.log(JSON.stringify(f
  ([ '4/2', '3/0', '0/8+2', '95-5', '4+2' ])
  ([ 6, 3, 4, 90, 2 ])
));

console.log(JSON.stringify(f
  ([ '7+4', '5-15', '212-23' ])
  ([ 11, 46, -2121 ])
));

console.log(JSON.stringify(f
  ([ '4+8/2-9*1', '99/3-13', '1+2+3+4', '4-3-2-1' ])
  ([ -5, 20, 10, -6 ])
));

console.log(JSON.stringify(f
  ([ '18/18', '98-8', '55*88', '-5--15' ])
  ([ 1, 90, 4840, 10 ])
));

console.log(JSON.stringify(f
  ([ '9119', '5-3', '8*-9', '13116/3' ])
  ([ 18, 513, 152, -1 ])
));
```

### Formatted and commented

```
e => r =>                                  // given e and r
  (l = [...2 ** 29 + '4+-*/'])             // generate l = [...'5368709124+-*/']
  .filter(x =>                             // for each character x of l
    l.some(y =>                            // for each character y of l
      eval("try {                          // we need to 'try', because we don't know
        eval(                              // whether the following expression is valid
          (S = (s = `[${e}]`).             // s = list of equations coerced to a string
            replace(/./g, c =>             // S =
              c == x ? y : c == y ? x : c  //   s with x and y exchanged
            )                              // end of replace()
          ).split`--`.join`+`              // replace '--' with '+'
        ) + '' == r                        // does the resulting list match r?
        & S != s                           // and was at least one character modified?
      } catch(e){}")                       // if we try, we oughta catch
    )                                      // end of some()
  )                                        // end of filter()

```

# Answer
> 4 votes
# Oracle SQL & PL/SQL, 458 Bytes

> Input can be in any reasonable format. \[...\] a list with equations and another list with the correct results.

Compile the PL/SQL function (210 bytes):

```
CREATE FUNCTION f(x CHAR,y CHAR)RETURN NUMBER IS o NUMBER;BEGIN EXECUTE IMMEDIATE 'BEGIN :1:='||REPLACE(x,'--','- -')||';END;'USING OUT o;RETURN CASE o WHEN y THEN 1 END;EXCEPTION WHEN OTHERS THEN RETURN 0;END;

```

Run the SQL (248 bytes):

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM T,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM T)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

After having create a table `T` with the test data:

```
CREATE TABLE T(X,Y) AS
  SELECT '123',    3     FROM DUAL UNION ALL
  SELECT '8423',   252   FROM DUAL UNION ALL
  SELECT '4+4',    8     FROM DUAL UNION ALL
  SELECT '4*7-10', 417   FROM DUAL UNION ALL
  SELECT '9/3',    3     FROM DUAL UNION ALL
  SELECT '42-9',   -36   FROM DUAL

```

Output:

```
V V_1
- ---
2 *
* 2

```

**Previous Version**:

Assumed a string input like `'123 = 3'`:

Same PL/SQL function and the SQL (322 bytes):

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15),y(x,y)AS(SELECT REGEXP_SUBSTR(t,'[^=]+'),REGEXP_SUBSTR(t,'-?\d+$')FROM T)SELECT r.v,s.v FROM y,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM T)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

After having create a table `T` with the test data:

```
CREATE TABLE T(T) AS
  SELECT '123    = 3'   FROM DUAL UNION ALL
  SELECT '8423   = 252' FROM DUAL UNION ALL
  SELECT '4+4    = 8'   FROM DUAL UNION ALL
  SELECT '4*7-10 = 417' FROM DUAL UNION ALL
  SELECT '9/3    = 3'   FROM DUAL UNION ALL
  SELECT '42-9   = -36' FROM DUAL;

```

Output:

```
V V_1
- ---
2 *
* 2

```

**Update - Testing**:

SQL Fiddle

**Oracle 11g R2 Schema Setup**:

```
CREATE FUNCTION F(x CHAR,y CHAR)RETURN NUMBER IS o NUMBER;BEGIN EXECUTE IMMEDIATE 'BEGIN :1:='||REPLACE(x,'--','- -')||';END;'USING OUT o;RETURN CASE o WHEN y THEN 1 END;EXCEPTION WHEN OTHERS THEN RETURN 0;END;
/

CREATE TABLE A(X,Y) AS
  SELECT '123',    3     FROM DUAL UNION ALL
  SELECT '8423',   252   FROM DUAL UNION ALL
  SELECT '4+4',    8     FROM DUAL UNION ALL
  SELECT '4*7-10', 417   FROM DUAL UNION ALL
  SELECT '9/3',    3     FROM DUAL UNION ALL
  SELECT '42-9',   -36   FROM DUAL
/

CREATE TABLE B(X,Y) AS
  SELECT '4/2',    6     FROM DUAL UNION ALL
  SELECT '3/0',    3     FROM DUAL UNION ALL
  SELECT '0/8+2',  4     FROM DUAL UNION ALL
  SELECT '95-5',   90    FROM DUAL UNION ALL
  SELECT '4+2',    2     FROM DUAL
/

CREATE TABLE C(X,Y) AS
  SELECT '7+4',    11    FROM DUAL UNION ALL
  SELECT '5-15',   46    FROM DUAL UNION ALL
  SELECT '212-23', -2121 FROM DUAL
/

CREATE TABLE D(X,Y) AS
  SELECT '4+8/2-9*1', -5 FROM DUAL UNION ALL
  SELECT '99/3-13',   20 FROM DUAL UNION ALL
  SELECT '1+2+3+4',   10 FROM DUAL UNION ALL
  SELECT '4-3-2-1',   -6 FROM DUAL
/

CREATE TABLE E(X,Y) AS
  SELECT '18/18',  1     FROM DUAL UNION ALL
  SELECT '98-8',   90    FROM DUAL UNION ALL
  SELECT '55*88',  4840  FROM DUAL UNION ALL
  SELECT '-5--15', 10    FROM DUAL
/

CREATE TABLE G(X,Y) AS
  SELECT '9119',    18   FROM DUAL UNION ALL
  SELECT '5-3',     513  FROM DUAL UNION ALL
  SELECT '8*-9',    152  FROM DUAL UNION ALL
  SELECT '13116/3', -1   FROM DUAL
/

```

**Query 1**:

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM A,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM A)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

**Results**:

```
| V | V |
|---|---|
| 2 | * |
| * | 2 |

```

**Query 2**:

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM B,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM B)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

**Results**:

```
| V | V |
|---|---|
| + | / |
| / | + |

```

**Query 3**:

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM C,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM C)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

**Results**:

```
| V | V |
|---|---|
| 1 | - |
| - | 1 |

```

**Query 4**:

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM D,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM D)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

**Results**:

```
| V | V |
|---|---|
| 2 | 4 |
| 4 | 2 |

```

**Query 5**:

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM E,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM E)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

**Results**:

```
| V | V |
|---|---|
| 5 | 8 |
| 8 | 5 |

```

**Query 6**:

```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM G,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM G)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0

```

**Results**:

```
| V | V |
|---|---|
| 1 | - |
| - | 1 |

```

# Answer
> 4 votes
# Python 2, ~~204~~, ~~199~~, ~~193~~, ~~173~~, 165 bytes

* From 199 bytes to 193 bytes thanks to Mr. Xcode
* From 193 bytes to 173 bytes thanks to Halvard Hummel

```
s=input()
r=str.replace
t=set(''.join(zip(*s)[0]))
for i in t:
 for j in t:
	try:
	 if all(eval(r(r(r(e,i,'$'),j,i),'$',j))==v*(i<j)for e,v in s):print i,j
	except:0

```

Try it online!

# Answer
> 2 votes
# Powershell, ~~222~~ ~~209~~ 192 bytes

```
param($x)1..13|%{0..(($i=$_)-1)|%{$a,$b='+-*/0123456789'[$i,$_]
$a+$b|?{!($x|%{$e,$r=$_-split'='
try{$r-(-join$(switch($e|% t*y){$a{$b}$b{$a}default{$_}})-replace'-',' -'|iex)}catch{1}}|gu)}}}

```

Test script and explanation:

```
$f={

param($x)                               # array of strings with equations
1..13|%{                                #
    0..(($i=$_)-1)|%{                   # $i and $_ contains unique couples of different indecies
        $a,$b='+-*/0123456789'[$i,$_]  # $a and $b contains buttons to swap
        $g=$x|%{                        # for each equation from array
            $e,$r=$_-split'='           # split incorrect expression and correct result
            $e=-join$(switch($e|% t*y){ # swap buttons for each symbol in the expression
                $a{$b}
                $b{$a}
                default{$_}
            })
            $e=$e-replace'-',' -'       # insert a space before each '-'.
                                        # It need to work with negative numbers.
                                        # For example, '4--1' throws an exception, '4 - -1' returns '5'
            try{$r-($e|iex)}catch{1}    # Try to calc $e as powershell expression
                                        # return 0 if the expression result equal to the result of the calculation
                                        # return non zero integer otherwise
        }|gu                            # Get-unique of calculation for each equation
        if(!$g){                        # if $g is 0 or $null
                                        # then all calculations returns true
            $a+$b                       # Ok, return the couple of buttons
        }
    }
}

}

@(
    ,('2*','123=3','8423=252','4+4=8','4*7-10=417','9/3=3','42-9=-36')
    ,('/+','4/2=6','3/0=3','0/8+2=4','95-5=90','4+2=2')
    ,('1-','7+4=11','5-15=46','212-23=-2121')
    ,('42','4+8/2-9*1=-5','99/3-13=20','1+2+3+4=10','4-3-2-1=-6')
    ,('1-','9119=18','5-3=513','8*-9=152','13116/3=-1')
) | % {
    $e,$x=$_
    $r=&$f $x
    "$($e-eq$r): $r : $x"
}

```

Output:

```
True: 2* : 123=3 8423=252 4+4=8 4*7-10=417 9/3=3 42-9=-36
True: /+ : 4/2=6 3/0=3 0/8+2=4 95-5=90 4+2=2
True: 1- : 7+4=11 5-15=46 212-23=-2121
True: 42 : 4+8/2-9*1=-5 99/3-13=20 1+2+3+4=10 4-3-2-1=-6
True: 1- : 9119=18 5-3=513 8*-9=152 13116/3=-1

```

# Answer
> 0 votes
# 05AB1E, 21 bytes

```
SÙãʒË_}ʒ¹sÂ‡„--'+:.EQ

```

Input as two lists, first being the equations and second being the results. Output as a filtered list of pairs with both rotations (i.e. `[["2","*"],["*","2"]]`).

Try it online or verify all test cases. (NOTE: Uses the legacy version of 05AB1E in the TIO, because `.E` is disabled in the newer version on TIO. Because of that, an additional `ï` (cast to integer) is added, because in the legacy version of 05AB1E `1.0` and `1` inside lists were not equal.)

**Explanation:**

```
S              # Convert the (implicit) input-list of equations to a list of characters
               # (which implicitly flattens)
               #  i.e. ["18/18","98-8","55*88","-5--15"]
               #   → ["1","8","/","1","8","9","8","-","8","5","5","*","8","8","-","5","-","-","1","5"]
 Ù             # Only leave all unique characters
               #  → ["1","8","/","9","-","5","*"]
  ã            # Cartesian product with itself; creating each possible pair of characters
               #  → [["1","1"],["1","8"],["1","/"],["1","9"],["1","-"],["1","5"],["1","*"],["8","1"],["8","8"],["8","/"],["8","9"],["8","-"],["8","5"],["8","*"],["/","1"],["/","8"],["/","/"],["/","9"],["/","-"],["/","5"],["/","*"],["9","1"],["9","8"],["9","/"],["9","9"],["9","-"],["9","5"],["9","*"],["-","1"],["-","8"],["-","/"],["-","9"],["-","-"],["-","5"],["-","*"],["5","1"],["5","8"],["5","/"],["5","9"],["5","-"],["5","5"],["5","*"],["*","1"],["*","8"],["*","/"],["*","9"],["*","-"],["*","5"],["*","*"]]
    ʒ  }       # Filter it by:
     Ë_        #  Where both characters are unique
               #   i.e. → [["1","8"],["1","/"],["1","9"],["1","-"],["1","5"],["1","*"],["8","1"],["8","/"],["8","9"],["8","-"],["8","5"],["8","*"],["/","1"],["/","8"],["/","9"],["/","-"],["/","5"],["/","*"],["9","1"],["9","8"],["9","/"],["9","-"],["9","5"],["9","*"],["-","1"],["-","8"],["-","/"],["-","9"],["-","5"],["-","*"],["5","1"],["5","8"],["5","/"],["5","9"],["5","-"],["5","*"],["*","1"],["*","8"],["*","/"],["*","9"],["*","-"],["*","5"]]
    ʒ          # Then filter the pairs again by:
     ¹         #  Push the first input-list with equations
      s        #  Swap to take the pair we're filtering
       Â       #  Bifurcate it (short for Duplicate and Reverse)
        ‡      #  Transliterate; replacing the characters at the same indices in the input-list
               #   i.e. ["18/18","98-8","55*88","-5--15"] and ["8","5"]
               #    → ["15/15","95-5","88*55","-8--18"]
               #   i.e. ["9119","5-3","8*-9","13116/3"] and ["1","-"]
               #    → ["9--9","513","8*19","-3--6/3"]
      „--'+:  '#  Then replace all "--" with a "+"
               #   → ["15/15","95-5","88*55","-8+18"]
               #   → ["9+9","513","8*19","-3+6/3"]
      .E       #  And evaluate the strings with Python eval
               #   → [1.0,90,4840,10]
               #   → [18,513,152,-1.0]
        Q      #  And then check if this evaluated list is equal to the (implicit) second input
               #   i.e. [1.0,90,4840,10] and [1,90,4840,10] → 1 (truthy)
               #   i.e. [18,513,152,-1.0] and [18,513,152,-1] → 1 (truthy)
               # (and output the result implicitly)
               #   i.e. [["8","5"],["5","8"]
               #   i.e. [["1","-"],["-","1"]

```

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


title: Mis-decode a date

text:
# Question
Title: Mis-decode a date
## Background

Inspired by a now deleted question by John Burger from which I quote:

> Now obviously no human made this mistake. It's a mis-decode of something - perhaps the ISBN? My question is: does anyone know of an existing algorithm that was so messed up it would invent an entirely new calendar?

TFeld ingeniously commented:

> It seems that the book was published on `2008-09-16`, so maybe it was somehow read as `00809162` -\> `00=dec?`, `80`, `9162`

### Task

Given a date represented as a three-element list, answer with the corresponding three-element mis-decoded list.

Mis-decoding happens as follows (example for `[2008,9,16]` in parentheses):

1. Join the digits of the year, month, and day, inserting leading zeros as necessary (`"20080916"`)
2. Move the first digit to the end (`"00809162"`)
3. Split the eight digits into groups of two, two, and four (`"00","80","9162"`)
4. Interpret them as numbers (`[0,80,9162]`)
5. Normalise the month number by wrapping 0 around to 12, and wrapping 13 around to 1, 14 to 2, 15 to 3, …, 25 to 1 etc. (`[12,80,9162]`)
6. Rearrange the list to get the original order (`[9162,12,80]`)

* You may take the original date in any order, but your answer must use the same order. Please state any non-default order.
    * The given year will always have four digits, but dates in October will lead to a three- or two-digit answer year.
    * You may take a list of strings or a character-delimited string, but it may not include leading zeros and you must answer in the same format and again without leading zeros.

## Examples

`[1700,1,1]``[1011,10,0]`

`[1920,4,29]``[4291,8,0]`

`[1966,11,27]``[1271,12,61]`

`[1996,12,13]``[2131,3,61]`

`[2008,9,1]``[9012,12,80]`

`[2008,9,16]``[9162,12,80]`

`[1010,10,1]``[11,1,1]`

# Answer
> 3 votes
# Python 2, ~~95~~ ~~67~~ ~~66~~ ~~65~~ 64 bytes

```
lambda y,m,d,t=10,T=1000:(m%t*T+d*t+y/T,y%T/t%12or 12,y%t*t+m/t)

```

Try it online!

<sub>-1 byte, thanks to Chas Brown</sub>

---

Given the task description, I kinda had to try it :)

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 69 bytes

```
(y,m,d)=>(m%10*1000+d*10+y/1000,(d=y%1000/10%12)<1?12:d,y%10*10+m/10)

```

Try it online!

Lambda with 3 inputs (`y`,`m`,`d`) that returns a 3-value tuple that has the resulting date parts in the same order.

The result is calculated by shifting digits to the left and right using regular division and the modulo operator with different powers of 10.

The `d` variable is used to caputure the month calculation so that it can be returned or wrapped to 12 when 0.

# Answer
> 1 votes
# JavaScript, ~~74~~ ~~72~~ 65 bytes

Thanks @Shaggy for saving 2 bytes Thanks @Arnauld for saving 7 bytes

```
(a,b,c)=>[b%10*1e3+c*10+a/1e3|0,a/10%100%12|0||12,b/10|0+a%10*10]

```

Try it online!

Straight modular arithmetic. Receives 3 integers (Y,M,D) and returns an array of 3 integers (\[Y,M,D\])

# Answer
> 1 votes
# Japt, ~~46~~ ~~42~~ ~~32~~ 27 bytes

*-10 bytes thanks to fəˈnɛtɪk and -1 byte thanks to Shaggy*

```
ùT2 ¬éJ ò4 vò c mn v_%CªCÃé

```

Try it online

---

## Explanation:

```
ùT2 ¬éJ ò4 vò c mn v_%CªCÃé  // Full program
                             // Test input:                     [2008,9,16]
ù                            // Left-pad each item
  2                          //   To length 2                   ["2008"," 9","16"]
 T                           //   With "0"                      ["2008","09","16"]
   ¬                         // Join into a string               "20080916"
    éJ                       // Rotate counter-clockwise         "00809162"
       ò4                    // Cut into slices of length 4     ["0080","9162"]
          vò                 // Slice the first item into 2    [["00","80"],"9162"]
             c               // Flatten                         ["00","80","9162"]
               mn            // Cast each item into numbers     [0,80,9162]
                  v_         // Apply to the first item:        [0
                    %C       //   %12                           [0
                      ªC     //      ||12                       [12
                        Ã    // Escape v_                       [12,80,9162]
                         é   // Rotate clockwise                [9162,12,80]

```

# Answer
> 1 votes
# Jelly,  ~~19~~  18 bytes

-1 thanks to Erik the Outgolfer (`D¹ŻṖ?``d⁵DẎ`)

```
d⁵DẎ€Ẏṙ5ṁƲḌṃ2¦12Ṫ€

```

A monadic link accepting a list of integers which yields a list of integers.

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

### How?

```
d⁵DẎ€Ẏṙ5ṁƲḌṃ2¦12Ṫ€ - Link: list of integers, dt     e.g. [        1779,        3,        14]
d⁵                 - divmod 10 (vectorises)              [      [177,9],    [0,3],     [1,4]]
  D                - to decimal digits                   [[[1,7,7],[9]],[[0],[3]],[[1],[4]]]]
   Ẏ€              - tighten €ach:                       [    [1,7,7,9],    [0,3],     [1,4]]
         Ʋ         - last four links as a monad (call that x):
     Ẏ             -   tighten x                         [     1,7,7,9,      0,3,       1,4]
       5           -   literal five
      ṙ            -   rotate (left) left by (right)     [     3,1,4,1,      7,7,       9,0]
        ṁ          -   mould like x                      [    [3,1,4,1],    [7,7],     [9,0]]
          Ḍ        - from decimal digits                 [         3141,       77,       90]
             ¦     - sparse application: {
            2      -   to indices: literal two                                 77
           ṃ  12   -   do: base decompress using [1..12]                    [6,5]
                   - }                                   [         3141,    [6,5],       90]
                Ṫ€ - tail €ach                           [         3141,       5,        90]

```

# Answer
> 1 votes
# Python 3, ~~126~~ 111 bytes

Input and output as a list of strings. Probably could be shorter if I can rewrite this as a `lambda`.

```
def f(d):d=d[0][1:]+d[1].zfill(2)+d[2].zfill(2)+d[0][0];return[d[4:],str((int(d[:2])-1)%12+1),str(int(d[2:4]))]

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 78 bytes

```
,(.\b)?
$#1$*0$1
(.)(..)(..)(...)
$4$1;11$*1$2$*1,$3$*
;(1{12})*
,1
,(1*)
,$.1

```

Try it online! Link includes test cases. Explanation:

```
,(.\b)?
$#1$*0$1

```

Replace the commas with zeros or just delete them for 2-digit numbers.

```
(.)(..)(..)(...)
$4$1;11$*1$2$*1,$3$*

```

Rearrange the year and extract the mis-decoded month and day in unary, adding 11 to the month.

```
;(1{12})*
,1

```

Reduce the month modulo 12 and add 1, bringing it into the desired range.

```
,(1*)
,$.1

```

Convert the month and day back to decimal without leading zeros.

# Answer
> 0 votes
# 05AB1E, 22 bytes

```
T‰JJ5._422S£εïNi12LÁsè

```

Try it online or verify all test cases.

**Explanation:**

```
T‰                       # Divmod each value in the (implicit) input with 10
                         #  i.e. [4291,8,0] → [[429,1],[0,8],[0,0]]
                         #  i.e. [2000,10,1] → [[200,0],[1,0],[0,1]]
  JJ                     # Then join everything together into a single string
                         #  i.e. [[429,1],[0,8],[0,0]] → "42910800"
                         #  i.e. [[200,0],[1,0],[0,1]] → "20001001"
    5._                  # Rotate it 5 times towards the left
                         #  i.e. "42910800" → "80042910"
                         #  i.e. "20001001" → "00120001"
       422S£             # Split it into parts of size 4,2,2
                         #  i.e. "80042910" → ["8004","29","10"]
                         #  i.e. "00120001" → ["0012","00","01"]
            ε            # Map each part to:
             ï           # Cast the string to an integer (removing leading zeros)
                         #  i.e. ["8004","29","10"] → [8004,29,10]
                         #  i.e. ["0012","00","01"] → [12,0,1]
              Ni         # And if the index is exactly 1:
                12L      # Push the list [1,2,3,4,5,6,7,8,9,10,11,12]
                   Á     # Rotate once towards the right: [12,1,2,3,4,5,6,7,8,9,10,11]
                    s    # Swap to get the map item
                     è   # And index it into the list (with automatic wraparound)
                         #  i.e. 0 → 12
                         #  i.e. 29 → 5
                         # (output the resulting list implicitly)
                         #  i.e. [8004,5,10]
                         #  i.e. [12,12,1]

```

# Answer
> 0 votes
# Clojure, 178 bytes

An anonymous function that takes a sequence of integers (Y M D) as input.

```
#(let[s(apply format"%d%02d%02d"%)](let[[w x y z](map(fn[a](read-string(apply str\1\0\r a)))(partition 2(concat(rest s)[(first s)])))n(rem w 12)][(+(* 100 y)z)(if(= n 0)12 n)x]))

```

Try it online!

# Answer
> 0 votes
# Pyth, 31 bytes

```
.e?tkb@S12tbvc.>sm.[\02`dQ3j46T

```

Try it online here, or verify all the test cases at once here.

```
.e?tkb@S12tbvc.>sm.[\02`dQ3j46T   Implicit: Q=eval(input()), T=10
                                    # Example input: [2008,9,16]
                 m       Q        Map each element of Q, as d, using:
                       `d           Stringify d
                  .[                Pad the above on the left...
                      2             ... to length of a multiple of 2...
                    \0              ... with "0"
                s                 Concatenate into a single string
                                    # '20080916'
              .>          3       Rotate 3 positions to the right
                                    # '91620080'
             c             j46T   Chop the above at indexes 4 and 6 (j46T -> 46 to base 10 -> [4,6])
                                    # ['9162', '00', '80']
            v                     Evaluate each element of the above as a numeric
                                    # [9162, 0, 80]
.e                                Map each element of the above, as b with index k, using:
  ?tk                               If k-1 is nonzero...
     b                              ... yield b, otherwise...
      @S12                          ... look up in [1-12]...
          tb                        ... element with index b-1 (modular indexing)
                                    # [9162, 12, 80]
                                  Implicit print result of previous map

```

# Answer
> 0 votes
# Perl 6, 58 bytes

```
{m/(.)(..)(..)(...)/;$3~$0,$1%12||12,+$2}o*.fmt('%02d','')

```

Try it online!

Returns the year with leading zeros.

---
Tags: code-golf, string, number, date, encoding
---


# Question
Title: Find the smallest prime from a substring
In 1946 Erdos and Copeland proved that a certain number is a normal number, i.e. the digits in its decimal expansion are uniformly distributed.

Users will input a sequence of digits and you will find the smallest prime that contains that string in base 10.

Example:

```
input   -> output
"10"    -> 101
"03"    -> 103
"222"   -> 2221
"98765" -> 987659

```

**Shortest code in bytes** wins. I do know that some languages (mathematica, sage, pari-gp...) come with built-in functions related to primes. **-50 bytes** if your program doesn't rely on such functions. Don't try to cheat on this please, if your language already has a huge advantage don't claim the bonus.

## Edit

According to a few comments below, the smallest prime that contains "03" is 3. Does this really make a difference? The only thing I can think of is that maybe numbers are easier to handle than strings.

In cases like "03" the preferred output would be 103. However, I don't consider it to be the fundamental part of your program, so you're free to ignore any leading zero if it grants you a lower byte count.

# Answer
> 13 votes
# Golfscipt, ~~33~~ 32 bytes = -18 score

```
2{:x,2>{x\%!},!!x`3$?)!|}{)}/;;x

```

Explanation:

* `2{...}{)}/` \- starting with `2`, while something is true, increment the top of the stack
* `;;x` \- discard the intermediate values collected by `{}{}/` and the input, then put the last value tested there
* `:x,2>` \- store the value as `x`, then produce a list from `2` to `x-1`
* `{x\%!},!!` \- keep those that `x` is divisible by, then coerce to boolean (not empty)
* `x`3?)!` \- look up the input in the text form of `x` (`-1` if not found), increment, negate.
* `|` \- or

# Answer
> 7 votes
### Haskell program, 97 characters = 47 score

```
main=getLine>>= \i->print$head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x]

```

### Haskell function, 75 characters = 25 score

```
p i=head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x]

```

the type of `p` is `(Integral a, Show a) => [Char] -> a`. If you supply your own integral type, you can lookup by infix in your own representation of those values. The standard `Integer` uses the expected decimal notation for integers.

Not very fast. Quadratic in the value (not size) of the output.

ungolfed version:

```
import Data.List
leastPrime infix = head $ filter prime' [2..]
  where prime' x  = all (\n-> x`mod`n /= 0) [2..x-1]
                 && i `isInfixOf` show x
main = print . leastPrime =<< getLine

```

example:

```
Prelude> let p i=head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x]
Prelude> p "0"
101
Prelude> p "00"
1009
Prelude> p "000" -- long pause
10007

```

# Answer
> 3 votes
**Java - 175 characters.**

```
class s{public static void main(String[]a){int i,n=2,p;for(;;){p=1;for(i=3;i<n;i++)if(n%i==0)p=0;if((n==2||p>0)&&(""+n).indexOf(a[0])>=0) {System.out.println(n);break;}n++;}}}

```

# Answer
> 3 votes
# Mathematica 58

```
(n=1;While[StringCases[ToString[p=Prime@n],#]=={},n++];p)&

```

---

**Relative Timings** on my Mac (2.6 GHz i7 with 8 GB memory).

Find the smallest prime containing "01".

```
AbsoluteTiming[(n = 1; While[StringCases[ToString[p = Prime@n], #] == {}, n++]; p) &["01"]]

```

> {0.000217, 101}

---

Find the smallest prime containing "012345".

```
AbsoluteTiming[(n = 1; While[StringCases[ToString[p = Prime@n], #] == {}, n++]; p) &["012345"]]

```

> {5.021915, 10123457}

---

Find the smallest prime containing "0123456".

```
AbsoluteTiming[(n = 1; While[StringCases[ToString[p = Prime@n], #] == {}, n++]; p) &["0123456"]]

```

> {87.056245, 201234563}

# Answer
> 2 votes
# Sage, 72

Runs in the interactive prompt

```
a=raw_input()
i=0
p=2
while a not in str(p):i+=1;p=Primes().unrank(i)
p

```

`Primes().unrank(i)` gives the `i`th prime number, with the 0th prime being 2.

# Answer
> 2 votes
### R, 56chars -50 = 6

```
k=2;n=scan(,"");while(!grepl(n,k)|sum(!k%%2:k)>1)k=k+1;k

```

Take input as stdin. Increments k until k is a prime (tested by summing the instances for which k mod 2 to k are zeroes, hence FALSE since 0 turned into a logical is FALSE) and contains the string given as input (tested with a simple grep, here grepl since we want a logical as result).

Usage:

```
> k=2;n=scan(,"");while(!grepl(n,k)|sum(!k%%2:k)>1)k=k+1;k
1: "03"
2:
Read 1 item
[1] 103
> k=2;n=scan(,"");while(!grepl(n,k)|sum(!k%%2:k)>1)k=k+1;k
1: "003"
2:
Read 1 item
[1] 2003

```

# Answer
> 2 votes
# shell oneliner (coreutils): 45chars

Not defining a function here... just a oneliner that takes one argument in `$n` and scans the integer range (actually a bit more to make code shorter). The 55 character version:

```
seq 5e9|grep $n|factor|awk '{if(NF==2)print $2}'|head -n1

```

It's not even too slow. For `n=0123456` it returns `201234563` in `81.715s`. That's impressively fast for a long pipeline with two string processors.

Removing two characters (down to 53) and one pipe, we can get it running even faster:

```
seq 5e9|grep $n|factor|awk '{if(NF==2){print $2;exit}}'

```

And finally, some `sed` wizardry to bring it down to **45 characters**, although the printout is ugly:

```
seq 5e9|grep $n|factor|sed -n '/: \w*$/{p;q}'

```

> n=000 -\> 10007: 10007 (user 0.017s)
>
> n=012345 -\> 10123457: 10123457 (user 7.11s)
>
> n=0123456 -\> 201234563: 201234563 (user 66.8s)

# Answer
> 2 votes
# J - 38 char -50 = -12 pts

Normally in J, you'd be using the very optimized builtins dedicated to primes, so I'm not going to apologize for any slowness in execution.

```
>:@]^:(>./@(E.":)*:]=*/@(+.i.)@])^:_&2

```

Explained:

* `>:@]^:(...)^:_&2` \- Starting with 2, increment until `(...)` returns false.
* `(+.i.)@]` \- Take the GCD of the counter with every integer smaller than it. (We use the convention GCD(X,0) = X.)
* `]=*/@` \- Take the product of all these numbers, and test for equality to the counter. If the counter is prime, the list was all 1s, except for the GCD with 0; else there will be at least one GCD that is greater than 1, so the product will be greater than the counter.
* `>./@(E.":)` \- Test if the string representation of the counter (`":`) contains the string (`E.`) at any point. `>./` is the max function, and we use it because `E.` returns a boolean vector with a 1 wherever the substring begins in the main string.
* `*:` \- Logical NAND the results together. This will be false only if both inputs were true, i.e. if the counter both was prime and contained the substring.

Usage:

```
   >:@]^:(>./@(E.":)*:]=*/@(+.i.)@])^:_&2 '03'
103
   >:@]^:(>./@(E.":)*:]=*/@(+.i.)@])^:_&2 '713'
2713

```

For posterity, here's the version using the prime builtin (30 char long, but no bonus):

```
>:@]^:(>./@(E.":)*:1 p:])^:_&2

```

`1 p:]` tests the counter for primality, instead of the GCD trick.

# Answer
> 2 votes
# Brachylog (v2), 3 bytes in Brachylog's encoding

```
ṗ≜s

```

Try it online!

Function submission, taking input from the right-hand argument, giving output by mutating the left-hand argument. (This is the opposite of the normal Brachylog convention; see this meta post for more discussion. Swapping the arguments into the more usual order would cost three bytes.) The TIO link has a wrapper which calls the function with the appropriate calling convention and prints the result.

## Explanation

```
ṗ≜s
 ≜   Find the integer closest to zero
ṗ      which is prime {implicit: and output it via the left argument}
  s    and which is a substring of the {right argument}

```

Sadly, Brachylog is so appropriate for this problem that according to the rules in the problem, I can't even attempt to go for the bonus (which ironically means that it's incapable of winning).

One of the reasons I like Brachylog so much is that programming is a communication between human and computer, and thus a "perfect" language would let you just translate the problem specification into English directly; the ideas via which the problem was stated, and via which the program is written, would be the same. Brachylog can hit this ideal surprisingly often; the question here is "find the smallest prime containing a given substring", and I can literally string together the concepts of "smallest, prime, containing substring" in the correct order and have a working program. As such, Brachylog says much more about the nature of communication than a language in which you had to explicitly specify an algorithm for solving the problem would; sometimes when talking to other humans, we try to explain a problem by explaining the steps you'd take to solve it, but that's rare. So why should our languages be any different?

# Answer
> 1 votes
# JavaScript 83 bytes = 33 score

Golfed:

```
for(s=prompt(n=x=0);!n;x++)for(n=(''+x).match(s)?2:0;n&&n<x;n=x%n?n+1:0);alert(x-1)

```

Ungolfed (a bit):

```
s=prompt() // get the input
n = 0
for(x=0;!n;x++) // stop when n is non-zero
    if ((''+x).match(s)) { // if x matches the pattern, check if x is prime
        for(n=2;n&&n<x;)
            n = (x%n == 0) ? 0 : n+1; // if x%n is zero, x is not prime so set n=0
        // if n is non-zero here, x is prime and matches the pattern
    }
alert(x-1)

```

# Answer
> 0 votes
# Javascript (Node.JS) - 93 bytes = 43 points

```
l:for(i=x=process.argv[2];j=i;i++){while(--j>2)if(!(i%j*(""+i).match(x)))continue l
throw i}

```

In extracted form with sensible variable names:

```
outerLoop:for (currentTry=inputNumber=process.argv[2]; primeIterator=currentTry; currentTry++ ) {
    while (--primeIterator > 2)
        if(!(currentTry % primeIterator * (""+currentTry).match(inputNumber)))
            continue outerLoop;
    throw i
}

```

# Answer
> 0 votes
# Rust 0.9 136 bytes = 86 points

```
fn main(){
   let mut n:u32=2;
   while n.to_str().find_str(std::os::args()[1])==None ||
         range(2,n).find(|&x|n%x==0)!=None {
      n=n+1;
   }
   print!("{}",n);
}

```

Very explicit despite for compactness. Too much space spent on the string find. :(

Here the version without whitespace (136 char)

```
fn main(){let mut n:u32=2;while n.to_str().find_str(std::os::args()[1])==None||range(2,n).find(|&x|n%x==0)!=None{n=n+1;}print!("{}",n);}

```

# Answer
> 0 votes
# Japt, 10 bytes

```
_j *ZsøU}a

```

Try it

# Answer
> 0 votes
# Python 3, ~~80~~ 79 bytes - 50 = ~~30~~ 29 score

-1 byte thanks to @ASCII-only's creative use of `%s` instead of `str`

~~Test case "98765" has not been confirmed yet because of how long it is taking to test~~ Confirmed for test case "98765" after a couple of hours, but with a similar approach that utilizes short-circuit evaluation to avoid some primality testing it works much faster. Alternatively, this can be ~2x as fast if we know that "2" is not an input (we can avoid checking even numbers for primality) by setting `i=3` initially and `i+=2` in the loop, at no extra byte cost.

```
def f(x):
 i=2
 while(x in"%s"%i)*all(i%j for j in range(2,i))-1:i+=1
 return i

```

Try it online!

Explanation of the `while` condition (`(x in"%s"%i)*all(i%j for j in range(2,i))-1`):

`(x in"%s"%i)`: `True`/`1` if the current counter contains the desired sequence of numbers in it; `False`/`0` otherwise.

`all(i%j for j in range(2,i))`: `True`/`1` if the current counter always has a remainder when divided by any integer from 2 (inclusive) to itself (exclusive), i.e. is prime; `False`/`0` otherwise.

The `*` multiplies the two conditions together, and acts as an `and` operator - the product is `True`/`1` if and only if both conditions are `True`/`1`.

The `-1` acts as a `not` operator: `False`/`0` \- 1 results in `-1`, which is considered true, whereas `True`/`1` \- 1 results in `0`, which is considered false. Thus, the loop continues while the number either does not contain the desired sequence of numbers or is not prime.

Replace the `*` with `and` and add parentheses around everything but the `-1` for a much faster, equivalent solution (that is slightly longer).

A **76 byte - 50 = 26 score** solution in Python 2 given by @ASCII-only (utilizes ```` instead of `str()`,

```
def f(x):
 i=2
 while(x in`i`)*all(i%j for j in range(2,i))-1:i+=1
 return i

```

Try it online!

# Answer
> 0 votes
# Tidy, 37 bytes

```
{s:s&{s,p:s in"".p}from primes|first}

```

Try it online!

# Answer
> 0 votes
# Perl 6, 36 - 50 = -14 points

```
{$^a;first {/$a/&&$_%%one ^$_},2..*}

```

Try it online!

Considering `$_%%one ^$_` is the only 2 bytes ~~smaller~~ larger than `.is-prime`, I think it's worth it for the bonus. This times out for the last test case.

### Explanation:

```
{                                  }  # Anonymous code block
 $^a;                                 # Assign input to $a
     first                    ,2..*   # Find the first number
           {                 }        # Which
            /$a/                        # Contains the input
                &&                      # And
                  $_%%one ^$_           # Is prime

```

# Answer
> 0 votes
# JavaScript, 65 - 50 = 15 points

```
x=>(f=y=>(''+y).match(x)&&(p=n=>--n<2||y%n&&p(n))(y)?y:f(y+1))(x)

```

Try it online!

---
Tags: code-golf, primes
---


title: Code the Huffman!

text:
# Question
Title: Code the Huffman!
Or else he will huff and puff and blow your house down!

That was completely irrelevant. This challenge is actually about Huffman coding. The gist of it is the frequency of characters in a given text is utilized to make its representation shorter. In other words, let's say that our alphabet is `a` through `z` and space. That's 27 characters. Each of them can be uniquely encoded in just 5 bits because 5 bits have enough room for 32 characters. However, in many situations (like English, or languages in general), some characters are more frequent than others. We can use *fewer* bits for the more frequent characters and (perhaps) more bits for the less frequent characters. Done right, there is an overall savings in the number of bits and the original text can still be uniquely reconstructed.

Let's take "this question is about huffman coding" as an example. This text is 37 characters long, which would be 37\*8 = 296 bits normally, though only 37\*5 = **185 bits** if we only use 5 bits for each character. Keep that in mind.

Here is a (sorta) table of each character and their frequencies in the text, sorted from most to least frequent (where _ stands in for a space):

```
_ 5
i 4
n 3
o 3
s 3
t 3
u 3
a 2
f 2
h 2
b 1
c 1
d 1
e 1
g 1
m 1
q 1

```

An associated optimal coding could be:

```
_ 101
i 011
n 1100
o 1101
s 1110
t 1111
u 001
a 10011
f 0001
h 0101
b 00000
c 00001
d 01000
e 01001
g 10000
m 10001
q 10010

```

It should be immediately clear that this will be a better encoding than just using 5 bits for every character. Let's find out just how much better, though!

**145 bits**, compared with 185! That's a savings of 40 bits, or just over 20%! (This is, of course, assuming that information about the structure is available for decoding.) This coding is optimal because no more bits can be dropped by changing any character's representation.

## The task

* Write a program or function with one parameter that...
* Takes input from STDIN (or equivalent) or as a single argument.
* Output an optimal Huffman coding as above with the characters sorted by frequency (order within a frequency class doesn't matter).
* You may assume that the characters in the input are restricted to the ASCII range `32..126` plus a newline.
* You may assume the input is no longer than 10,000 characters (ideally, in theory, input should be unbounded).
* Your code should finish reasonably fast. The given example above should take no more than a minute or so at worst. (This is intended to rule out brute force.)
* Scoring is in bytes.

## Examples

```
x
---
x 0

xxxxxxxxx
---
x 0

xxxxxxxxy
---
x 0
y 1 (these may be swapped)

xxxxxyyyz
---
x 0
y 10
z 11

uuvvwwxxyyzz
---   (or)
u 000      000
v 001      001
w 100      010
x 101      011
y 01       10
z 11       11

this question is about huffman coding
---
  101
i 011
n 1100
o 1101
s 1110
t 1111
u 001
a 10011
f 0001
h 0101
b 00000
c 00001
d 01000
e 01001
g 10000
m 10001
q 10010

```

Happy coding!

---

Note that this similar question is closely related, even to the point that this one is a duplicate. However, the consensus so far on Meta is that the older one should be considered a duplicate of this one.

# Answer
> 2 votes
# Pyth, 53 bytes

```
jo_/zhNee.WtHa>JohNZ2+shKC<J2]s.b+RYNeKU2m,/zd]+d\ {z

```

Demonstration

Here's a version that shows the internal state, so you can see the encoding being built:

```
jo_/zhNee.WtHvp+`a>JohNZ2+shKC<J2]s.b+RYNeKU2bm,/zd]+d\ {z

```

Demonstration

Copy the output to an environment with wider lines for a clearer picture.

# Answer
> 4 votes
# Python 2, 299 bytes

Here's my attempt at an answer.

The Huffman codes are different from the examples given, but should still be optimal.

```
i=raw_input();m=n=[(c,i.count(c))for c in set(i)]
while n[1:]:n.sort(key=lambda x:(x[1]));(a,b),(c,d)=n[:2];n=[((a,c),b+d)]+n[2:]
n=n[0][0]
r=[]
def a(b,s):
 if b[1:]:a(b[0],s+'0');a(b[1],s+'1')
 else:r.append(b+(s if s[1:]else s+'0'))
a(n,' ')
for y in sorted(r,key=lambda x:-dict(m)[x[0]]):print y

```

# Answer
> 2 votes
# Matlab, 116 bytes

`tabulate` makes a frequency table. `huffmandict` takes a list of symbols and probabilities for each symbol, and calculates the code.

```
t=tabulate(input('')');
d=huffmandict(t(:,1),cell2mat(t(:,3))/100);
for i=1:size(d,1);disp([d{i,1},' ',d{i,2}+48]);end

```

# Answer
> 2 votes
# Ruby, ~~189~~ 180 bytes

Work in progress.

```
->s{m=s.chars.uniq.map{|c|[c,s.count(c)]}
while m[1]
(a,x),(b,y),*m=m.sort_by &:last
m<<[[a,b],x+y]
end
h={}
f=->q="",c{Array===c&&f[q+?0,c[0]]&&f[q+?1,c[1]]||h[c]=q}
f[m[0][0]]
h}

```

It's an anonymous function; assign it to something, for example `f`, and call it with

```
f["some test string"]`

```

which returns a hash like this:

```
{"t"=>"00", "g"=>"0100", "o"=>"0101", " "=>"011", "e"=>"100", "n"=>"1010", "i"=>"1011", "m"=>"1100", "r"=>"1101", "s"=>"111"}

```

# Answer
> 1 votes
## Haskell, 227 bytes

```
import Data.List
s=sortOn.(length.)
f x|[c]<-nub x=[(c,"0")]|1<2=g[(a,[(a!!0,"")])|a<-group$sort x]
g=h.s fst
h[x]=snd x
h((a,b):(c,d):e)=g$(a++c,map('0'#)b++map('1'#)d):e
n#(a,b)=(a,n:b)
p=unlines.map(\(a,b)->a:" "++b).s snd.f

```

Usage example:

```
*Main> putStr $ p "this question is about huffman coding"
u 000
i 011
  101
a 0010
f 0011
h 1000
s 1100
t 1101
n 1110
o 1111
d 01000
e 01001
b 01010
c 01011
q 10010
g 100110
m 100111

```

How it works:

`p` calls `f` which builds the Huffman table in the form of a list of (character,encoding)-pairs, e.g. `[ ('a',"0"), ('b',"1") ]`, sorts the table by length of encodings, formats each pair for output and joins with newlines in-between.

`f` first checks the single letter case and returns the corresponding table. Otherwise it sorts the input string and groups sequences of equal characters (e.g. `"ababa"` -\> `["aaa","bb"]`) and maps them to pairs `(sequence , [(char, "")])`, (-\> `[ ("aaa", [('a',"")]), ("bb", [('b', "")])]`. The first element is used to keep track of the frequency, the second element is a list of pairs of a character and it's encoding (which is initially empty). These are all single element Huffman tables as expected by `p` and are combined by `g` and `h`.

`g` sorts the list of pairs on the length of the first element, i.e. the frequency and calls `h`. `h` combines the Huffman tables of the first two elements, by concatenating the frequencies and putting a `0` (`1`) in front of every element of the first (second) table. Concatenate both tables. Call `g` again, stop when there's a single element left, throw away the frequency part and return the full Huffman table.

# Answer
> 1 votes
# K (ngn/k), 78 bytes

```
{h::0#'x;(#1_){{h[x],:!2;y,,,/x}.0 2_x@<#'x}/.=x;(?,/'x,'" ",'|'$h)(?x)?>#'=x}

```

Try it online!

returns a list of strings for printing

`h::0#'x` creates an empty list for each character (technically, it reshapes each character to length 0). we will store the reversed huffman codes there. we use `::` instead of `:` for assignment to make `h` global so it's visible in sub-functions.

`.=x` is a list of lists - the indices of the string grouped by character value

`(#1_)` is a function that returns truthy iff the length of the argument is \>1 (technically "length of 1 drop of ...")

`(#1_){`...`}/` means: while the argument has length \>1, keep applying the curly-brace function

`x@<#'x` sort the argument by length

`0 2_` cut it into a 2-element head and a tail

`{h[x],:!2;y,,,/x}` update `h` by appending 0 and 1 to the indices contained in the head; return the tail with the head as a single element

`(?,/'x,'" ",'|'$h)(?x)?>#'=x` reverse each of `h`, sort, unique, prepend corresponding characters, and format nicely

# Answer
> 0 votes
# JavaScript (ES6) 279

Essentially, the basic algorithm from Wikipedia. I probably can do better.

```
f=s=>{for(n=[...new Set(s)].map(c=>({c:c,f:[...s].filter(x=>x==c).length}));n[1];n.push({l:a=n.pop(),r:b=n.pop(),f:a.f+b.f,c:a.c+b.c}))n.sort((a,b)=>b.f-a.f);t=(n,b)=>(n.b=b,n.r)?(t(n.l,b+0),t(n.r,b+1)):o.push(n);t(n[0],'',o=[]);return o.sort((a,b)=>b.f-a.f).map(x=>x.c+' '+x.b)}

```

More readable inside the snippet below

```
f=s=>{
  for(n=[...new Set(s)].map(c=>({c:c,f:[...s].filter(x=>x==c).length}));
      n[1];
      n.push({l:a=n.pop(),r:b=n.pop(),f:a.f+b.f,c:a.c+b.c}))
    n.sort((a,b)=>b.f-a.f);
  t=(n,b)=>(n.b=b,n.r)?(t(n.l,b+0),t(n.r,b+1)):o.push(n);
  t(n[0],'',o=[]);
  return o.sort((a,b)=>b.f-a.f).map(x=>x.c+' '+x.b)
}

//TEST
console.log=x=>O.innerHTML+=x+'\n'

test=['xxxxxxxxy','uuvvwwxxyyzz','this question is about huffman coding']
.forEach(t=>console.log(t+'\n'+f(t).join`\n`+'\n'))
```

```
<pre id=O></pre>
```

---
Tags: code-golf, string, encoding, coding-theory
---


# Question
Title: Multi-level marketing "legs" investment rule
Multi-level marketing related challenge.

A peer wants to get rewarded. So it attracted `N` investors (`N>=1`), each i-th investor invested `x[i]`. When a total sum exceeds threshold `x[0]+x[1]+...+x[N-1] >= T` a peer could be rewarded. But only if a following conditions are satisfied:

* Minimum amount of investors should be greater than `M`, (`M<=N`)
* For at least one integer `k`, where `k>=M` and `k<=N`, any `k` investors have to invest at least `T/k` each;

Given `N, x[], T, M` you should determine whether the peer's reward is generated or not (boolean result, "yes" or "no"). Shortest code wins.

**Examples:**

---

`N=5; M=3; T=10000`, in order to generate the peer's reward one of the following must be satisfied:

* any 3 invested at least 3334 each
* any 4 invested at least 2500 each
* all 5 invested at least 2000 each

---

`N=6; M=2; T=5000`:

* any 2 invested at least 2500 each
* any 3 invested at least 1667 each
* any 4 invested at least 1250 each
* any 5 invested at least 1000 each
* all 6 invested at least 834 each

---

generalized: for any `k`, where `k>=M` and `k<=N`:

* any `k` of `N` investors invested at least `T/k` each

---

**Test cases:**

*format:*

`N, x[], T, M -> correct answer`

```
6, [999, 999, 59, 0, 0, 0], 180, 3 -> 0
6, [0, 60, 0, 60, 60, 0], 180, 3 -> 1
6, [179, 89, 59, 44, 35, 29], 180, 3 -> 0
6, [179, 89, 59, 44, 35, 30], 180, 3 -> 1
6, [179, 89, 59, 44, 36, 29], 180, 3 -> 1
6, [179, 90, 59, 44, 35, 29], 180, 3 -> 0
6, [30, 30, 30, 30, 29, 30], 180, 3 -> 0
6, [30, 30, 30, 30, 30, 30], 180, 3 -> 1

```

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

```
ṢṚ×J$ṫ⁵<Ṃ

```

A full program which accepts `x T M` and prints `0` if the peer is rewarded and `1` if not.

**Try it online!**

### How?

```
ṢṚ×J$ṫ⁵<Ṃ - Main Link: list of numbers, x; number, T   e.g. [100, 50, 77, 22, 14, 45], 180
Ṣ         - sort x                                          [ 14, 22, 45, 50, 77,100]
 Ṛ        - reverse                                         [100, 77, 50, 45, 22, 14]
    $     - last two links as a monad:
   J      -   range of length                               [  1,  2,  3,  4,  5,  6]
  ×       -   multiply                                      [100,154,150,180,110, 84]
     ṫ    - tail from index:
      ⁵   -   5th argument (3rd input), M   (e.g. M=3)      [        150,180,110, 84]
       <  - less than T?                                    [          1,  0,  1,  1]
        Ṃ - minimum                                         0

```

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
{Rƶ.ssè›ß

```

Try it online or verify all test cases.

Port of *@JonathanAllan*'s Jelly answer, so also takes the inputs `x T M` and outputs `0` for `"yes"` and `1` for `"no"`. If this is not allowed, and it should be inverted, a trailing `_` can be added.

**Explanation:**

```
{           # Sort the (implicit) input `x`
            #  i.e. `x`=[100,50,77,22,14,45] → [14,22,45,50,77,100]
 R          # Reverse it
            #  i.e. [14,22,45,50,77,100] → [100,77,50,45,22,14]
  ƶ         # Multiply it by it's 1-indexed range
            #  i.e. [100,77,50,45,22,14] → [100,154,150,180,110,84]
   .s       # Get all the suffices of this list
            #  i.e. [100,154,150,180,110,84]
            #   → [[84],[110,84],[180,110,84],[150,180,110,84],[100,154,150,180,110,84]]
     s      # Swap to take the (implicit) input `T`
      è     # Get the prefix at index `T`
            #  i.e. [[84],[110,84],[180,110,84],[150,180,110,84],[100,154,150,180,110,84]]
            #   and `T=3` → [150,180,110,84]
       ›    # Check for each list-value if the (implicit) input `M` is larger than it
            #  i.e. [150,180,110,84] and `M`=180 → [1,0,1,1]
        ß   # And pop and push the minimum value in the list (which is output implicitly)
            #  i.e. [1,0,1,1] → 0

```

---

Alternative for `.ssè`:

```
sG¦}

```

Try it online or verify all test cases.

**Explanation:**

```
s       # Swap to take the (implicit) input `T`
 G }    # Loop `T-1` times:
  ¦     #  Remove the first item from the list that many times
        #   i.e. [100,154,150,180,110,84] and `T=3` → [150,180,110,84]

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler) with flag `/u:System.Linq.Enumerable`, 69 bytes

```
(n,x,t,m)=>Range(0,n-m+1).Where(b=>x.Count(a=>a>=t/(b+m))>=b+m).Any()

```

Try it online!

```
// Takes in 4 parameters as input
(n,x,t,m)=>
// Create a new array with the length of all the numbers from m to n, inclusive
Range(0,n-m+1)
// And filter the results by
.Where((_,b)=>
// If the number of people that invested more than the total amount divided by the index plus m
x.Count(a=>a>=t/(b+m))
// Is greater than the index plus m
>= b+m)
// And check if there is at least one value in the filtered IEnumerable<int>, and if there is, return true
.Any()

```

# Without any flags, 73 bytes

```
(n,x,t,m)=>new int[n-m+1].Where((_,b)=>x.Count(a=>a>=t/(b+m))>=b+m).Any()

```

Try it online!

# Answer
> 2 votes
# JavaScript, ~~54~~ 52 bytes

```
(x,t,m,n)=>x.sort((a,b)=>a-b).some(i=>i*n-->=t&n>=m)

```

Try it online

# Answer
> 2 votes
# Retina, 79 bytes

```
\d+
*
O^`_+(?=.*])
_+(?=.*])(?<=(\W+_+)+)
$#1*$&
+`\W+_+(.*_)_$
$1
(_+).*], \1,

```

Try it online! Takes input in the format `[x], T, M`. Link includes test cases. Explanation:

```
\d+
*

```

Convert to unary.

```
O^`_+(?=.*])

```

Sort `[x]` in descending order.

```
_+(?=.*])(?<=(\W+_+)+)
$#1*$&

```

Multiply each element of `[x]` by its index.

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

```

Delete the first `M-1` elements of `[x]`.

```
(_+).*], \1,

```

Test whether any remaining element of `[x]` is greater or equal to `T`.

# Answer
> 2 votes
# Perl 6, ~~46 33~~ 29 bytes

```
{$^b>all $^a.sort Z*[...] @_}

```

Try it online!

Anonymous code blocks that takes input in the form `list, amount, length of list, minimum amount of investors` and returns a truthy/falsey `all` Junction, where truthy is failed and falsey is success.

### Explanation:

```
{                           }  # Anonymous code block
     all                       # Are all of
         $^a.sort                # The sorted list
                  Z*             # Zip multiplied by
                     [...] @_    # The range from length of list to the minimum amount
 $^b>                          # Not smaller than the given amount?

```

# Answer
> 2 votes
# 05AB1E, 6 bytes

Input taken in the order `T`, `N`, `x[]`, `M`
Output is `0` for peer reward and `1` if not

```
Ÿs{*›W

```

Try it online! or as a Test Suite

**Explanation**

```
Ÿ        # push the range [N ... T]
 s{      # push the list x[] sorted ascending
   *     # elementwise multiplication (crops to shortest list)
    ›    # for each element, check if M is greater than it
     W   # push min of the result
         # output implicitly

```

# Answer
> 2 votes
# C# (.NET Core), ~~129~~, 89 bytes

EDIT: Thanks to Kevin Cruijssen for golfing off 40 bytes while explaining the mechanics as to why!

```
(n,q,t,m)=>{int c=0,j;for(;m<=n&c<1;c=c<m++?0:1)for(j=n;j-->0;)c+=q[j]<t/m?0:1;return c;}

```

Try it online!

# Answer
> 1 votes
# JavaScript, 72 bytes

### Code

```
(x,T,M)=>x.sort(t=(d,e)=>e-d).map((s,i)=>s*i+s).slice(M-1).sort(t)[0]>=T

```

Try it online!

Accepts input in format (x\[\],T,M)

### Explanation

```
x.sort(t=(d,e)=>e-d)     \\sort numbers in reverse numerical order
.map((s,i)=>s*i+s)       \\Multiply each number in array by position(1 indexed) in array
.slice(M-1)              \\Remove the first M-1 elements (at least M people)
.sort(t)[0]              \\Get the maximum value in the array
>=T                      \\True if the maximum value is >= the threshold

```

# Answer
> 1 votes
# Python 3, 136 bytes

Just tests the conditions to make sure they are met. 1 if the reward is given, 0 if not.

```
lambda N,x,T,M:(sum(x)>=T)*(M<=N)*any(any(all(j>=T/k for j in i)for i in combinations(x,k))for k in range(M,N+1))
from itertools import*

```

Try it online!

# Answer
> 1 votes
# Japt, ~~16~~ ~~14~~ ~~13~~ 11 bytes

```
ñ í*WõX)d¨V

```

Try it

```
ñ í*WõX)d¨V
                  :Implicit input of array U=x and integers V=T, W=M & X=N
ñ                 :Sort U
  í               :Interleave with
    WõX           :  Range [W,X]
   *              :  And reduce each pair of elements by multiplication
       )          :End interleaving
        d         :Any
         ¨V       :  Greater than or equal to V

```

# Answer
> 1 votes
# Python,  ~~71~~  65 bytes

```
lambda x,T,M:all(i*v<T for i,v in enumerate(sorted(x)[-M::-1],M))

```

**Try it online!**

An unnamed function; port of my Jelly answer. As such "yes" is `False` and "no" is `True`. Here, however, we discard test-cases as a part of the reversal and take advantage of the ability to initiate the `enumerate` count to `M`. (`min` would also work in place of `all`)

# Answer
> 1 votes
# , ~~43~~ 42 bytes

*-1 bytes by implementing the approach even more closely*

```
function(N,x,S,M)min(sort(x,T)[M:N]*M:N<S)

```

Try it online!

Simple R implementation of Jonathan's Jelly approach. I tried a bunch of variations but this pips the best I could think of by a few bytes.

1 implies failure, 0 implies success.

# Answer
> 0 votes
# Java 8, 91 (or 89?) bytes

```
(N,x,T,M)->{int c=0,j;for(;M<=N&c<1;c=c<M++?0:1)for(j=N;j-->0;)c+=x[j]<T/M?0:1;return c;}

```

Port of *@Destroigo*'s C# .NET answer (after I golfed it some more), so make sure to upvote him!

Takes inputs `N,x,T,M` and outputs `true`/`false` for `"yes"`/`"no"` respectively.

Since the challenge specifically asks for `boolean` results, I can't return the `1`/`0` as is, since those aren't valid truthy/falsey values in Java. If any two distinct output values for `"yes"`/`"no"` is valid for this challenge instead, the `>0` in the return can be dropped to save two bytes, in which case it'll return `1`/`0` for `"yes"`/`"no"` respectively.

Try it online.

**Explanation:**

```
(N,x,T,M)->{           // Method with the four parameters and boolean return-type
  int c=0,             //  Count integer, starting at 0
      j;               //  Temp index integer
  for(;M<=N            //  Loop as long as `M` is smaller than or equal to `N`
       &c<1            //  and `c` is not 1 yet:
      ;                //    After every iteration:
       c=c<M++?        //     If `M` is smaller than `c`:
                       //     (and increase `M` by 1 afterwards with `M++`)
          0            //      Set `c` to 0
         :             //     Else:
          1)           //      Set `c` to 1
    for(j=N;j-->0;)    //   Inner loop `j` in the range (`N`,0]:
       c+=             //    Increase the counter `c` by:
          x[j]         //     If the `j`'th value in `x`
              <T/M?    //     is smaller than `T` divided by `M`:
                   0   //      Leave the counter `c` unchanged by adding 0
                  :    //     Else:
                   1;  //      Increase the counter `c` by 1
  return c>0;}         //  Return whether the counter `c` is 1

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 66 bytes

```
(n,x,t,m)=>Enumerable.Range(m,n-m+1).Any(k=>x.Count(y=>y>=t/k)>=k)

```

Try it online!

Inspired by @EmbodimentOfIgnorance's answer.

I've mentioned this before, but C# 8 has a range literal which could make this answer something like this:

```
(n,x,t,m)=>[m..n-m+1].Any(k=>x.Count(y=>y>=t/k)>=k)

```

I saw a link to SharpLab with an example, but I wasn't able to get it to work myself.

One thing I changed was the `x` and `t` values are decimals. This handles the case where `t` is not divisible by `k` a little better.

---
Tags: code-golf, decision-problem
---


title: Help the dealer rebuild the deck

text:
# Question
Title: Help the dealer rebuild the deck
The dealer has been sloppy and lost track of what cards his/her deck contains and what cards are missing, can you help him/her?

---

A complete deck consists of 52 playing cards, namely:

Each color in the deck (hearts, diamonds, spades, clubs) contains:

* The numbers \[2 - 10\]
* A Jack
* A Queen
* A King
* An Ace

---

**Task**

Your program will read the contents of the deck from STDIN until a newline is read. You can assume that the input will be in the form of "nX nX nX nX" etc. where:

* n - any number between \[2 - 10\] **or** either 'J', 'Q', 'K' or 'A'. (You can assume upper case only for non-numeric characters)
* X - any of the following : 'H', 'D', 'S', 'C' (You can assume upper case only)

Where:

* 'J' = Jacks
* 'Q' = Queen
* 'K' = King
* 'A' = Ace

And

* 'H' = Hearts
* 'D' = Diamonds
* 'S' = Spades
* 'C' = Clubs

You can assume that there will be no duplicates in the input.

Your program must then print the missing cards in the deck to STDOUT in the same fashion as the input ("nX nX nX") or print 'No missing cards' if all 52 cards are supplied. There is no constraint on the order of the output of the cards.

Example input:

```
9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S

```

Output:

```
3H 4H 5H 6H 7H 10H JH QH KH 2D 3D 5D 6D 8D 9D 10D QD 2S 4S 5S 7S 8S 9S QS KS 3C 4C 5C 6C 10C JC QC HC

```

Happy golfing!

# Answer
## Windows Batch (CMD), ~~205~~ 204 bytes

```
@set/pc=
@set d=
@for %%s in (H D S C)do @for %%r in (2 3 4 5 6 7 8 9 10 J Q K A)do @call set d=%%d%% %%r%%s
@for %%c in (%c%)do @call set d=%%d: %%c=%%
@if "%d%"=="" set d= No missing cards
@echo%d%

```

Loops over the suits and ranks building a complete deck, then deletes the input cards. Save 1 byte if `T` is allowed instead of `10`. Save 11 bytes if command-line arguments are acceptable input. Edit: Saved 1 byte thanks to @user202729.
> 8 votes

# Answer
# Python, ~~147~~ ~~146~~ ~~145~~ ~~138~~ ~~131~~ ~~129~~ ~~127~~ ~~125~~ 120 bytes

```
print(' '.join(set(`x`+y for x in range(2,11)+list('JQKA')for y in'HDSC')-set(raw_input().split()))or'No missing cards')

```

Gets all possible cards as a set and subtracts the input cards.

-1 byte thanks to mbomb007 pointing out an extra space in my code.
-1 byte thanks to mbomb007 for pointing out some golfing that can be done with Python 2 (-5 bytes and +4 bytes for `raw_` in `raw_input`)
-7 bytes by switching to using sets and set subtraction instead of list comprehensions
-7 bytes thanks to ValueInk for pointing out that I don't need to `list` the suites
-2 bytes thanks to Datastream for pointing out that just writing out all of the values is more byte-effective than the weird thing I had earlier
-2 bytes thanks to ValueInk for pointing out that sets can take generators so I don't need to put it in a list comprehension
-2 bytes thanks to Datastream for pointing out that I can golf it down even more if I switch to Python 3 again... (+2 for parens after for print, -4 for `raw_`)
-5 bytes thanks to Lulhum and myself for pointing out that by switching back to Python 2 (!!!) can help me save bytes (using range again, using backticks instead of `str(`, and +4 due to `raw_`)
> 8 votes

# Answer
# 05AB1E, 39 bytes

```
ðIð¡YTŸ"JQKA"S«"CDHS"SâJsKðýDg>i“Noœ¶‡¶

```

Try it online!

**Explanation**

```
ðI                                       # push space and input
  ð¡                                     # split on spaces
    YTŸ                                  # push the range [2 ... 10]
       "JQKA"S«                          # append ['J','Q','K','A']
               "CDHS"Sâ                  # cartesian product with suits
                       J                 # join each card with its suit
                        sK               # remove any cards in input from the list of all cards
                          ðýDg>i         # if the length of the resulting list is 0
                                “Noœ¶‡¶  # push the string "No missing cards"
                                         # output top of stack

```
> 7 votes

# Answer
# CJam, ~~49~~ 47 bytes

```
B,2>"JQKA"+"HDSC"m*:slS/-S*"No missing cards"e|

```

Try it online!

**Explanation**

```
B,                    e# The range from 0 to 10
2>                    e# Slice after the first two elements, giving the range from 2 to 10
"JQKA"+               e# Concatenate with "JQKA", giving the array containing all ranks
"HDSC"                e# The string containing all suits
m*                    e# Take the Cartesian product
:s                    e# And cast each pair to a string. Now a full deck has been constructed
l                     e# Read a line of input
S/                    e# Split it on spaces
-                     e# Remove all cards from the deck that were in the input
S*                    e# Join the result with spaces
"No missing cards"    e# Push the string "No missing cards"
e|                    e# Take the logical OR of the result and the string, returning the
                      e#   first truthy value between the two. (empty arrays are falsy)

```
> 5 votes

# Answer
# Jelly, 39 bytes

```
9R‘Ṿ€;“JQKA”p“CDHS”F€œ-ɠḲ¤Kȯ“¡¢ıḍĖ9ṭƥw»

```

**Try it online!**

### How?

```
9R‘Ṿ€;“JQKA”p“CDHS”F€œ-ɠḲ¤Kȯ“¡¢ıḍĖ9ṭƥw» - Main link: no arguments
9R                                      - range(1,9)    [1,2,3,4,5,6,7,8,9]
  ‘                                     - increment     [2,3,4,5,6,7,8,9,10]
   Ṿ€                                   - uneval each  [['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10']]
     ;“JQKA”                            - concatenate with char-list "JQKA" [['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10'],['J'],['Q'],['K'],['A']]
            p“CDHS”                     - Cartesian product with char-list "CDHS" [[['2'],['C']],[['2'],['D']],...]
                   F€                   - flatten each [['2','C'],['2','S'],...]
                         ¤              - nilad followed by link(s) as a nilad
                       ɠ                -     read a line from STDIN
                        Ḳ               -     split on spaces
                     œ-                 - multi-set difference
                          K             - join with spaces
                            “¡¢ıḍĖ9ṭƥw» - compressed string "No missing cards"
                           ȯ            - logical or
                                        - implicit print

```
> 5 votes

# Answer
# C#, 343 bytes

First time posting one of my golfs, not a very good contender though. I'm sure I can reduce this more.

The idea behind it is a sparse array storing occurrences of cards, with indexes calculated by the ASCII values of the different values and suits multiplied against each other (e.g. an ace of spades (AS) would be stored in the area at index (65 * 83 = 5395)). This way, each type of card gets a unique index that can be checked later for existance in the "map" array.

```
void M(string[]a){var c=new int[]
{50,51,52,53,54,55,56,57,49,74,81,75,65,72,68,83,67};var e=new
int[9999];int i=0;int j=0;foreach(var s in a) e[s[0]*s[s.Length-
1]]++;int f=0;for(i=0;i<13;i++)for(j=13;j<17;j++)if(e[c[i]*c[j]]==0)
{f=1;Console.Write(((i<9)?(i+2)+"":(char)c[i]+"")+(char)c[j]+"
");}if(f==0) Console.WriteLine("No missing cards");}

```
> 5 votes

# Answer
# PowerShell, ~~114~~ ~~111~~ 110 bytes

```
param($n)('No missing cards',($a=(2..10+'JQKA'[0..3]|%{$i=$_;"CSHD"[0..3]|%{"$i$_"}}|?{$n-notmatch$_})))[!!$a]

```

Try it online!

Takes input `$n` as either a space-delimited or newline-delimited string. Constructs an array from the range `2..10` concatenated with `JQKA` (indexed with `[0..3]` to make it a `char` array). That array is fed into a loop `|%{}` that sets helper `$i` then loops over the suits to concatenate the results together with `$i$_`. At the end of this loop, we have an array of strings like `("2C", "2S", "2H", ... "AH", "AD")`. That array is fed into a `Where-Object` (`|?{}`) with the filter as those elements `$_` that regex `-notmatch` the input `$n`. The result of that filtering is stored into `$a`.

Then, we use a pseudo-ternary `( , )[]` to select whether we output `'No missing cards'` or `$a`, based on whether `!!$a` turns to a Boolean `$false` or `$true`. If `$a` is empty (meaning every card in the deck is in the input), then `!!$a` is `0`, so the `"No missing cards"` is selected. Vice versa for `$a` being selected. In either case, that's left on the pipeline, and output is implicit.
> 4 votes

# Answer
# Bash + coreutils, 89

```
sort|comm -3 <(printf %s\\n {10,{2..9},A,J,K,Q}{C,D,H,S}) -|grep .||echo No missing cards

```

I/O as a newline-delimited list.

### Explanation

* `sort` reads newline-delimited input from STDIN and sorts it
* This is piped to `comm`
* `printf %s\\n {10,{2..9},A,J,K,Q}{C,D,H,S}` is a brace-expansion to generate the full deck of cards. The `printf` prints each card on its own line. The order is given such that the output is the same as if it had been piped to `sort`
* `comm` compares the full deck against the sorted input and outputs the difference. `-3` suppresses output of column 3 (the common ones)
* The whole output from `comm` is piped to `grep .`. If there was no output from `comm` (i.e. all cards were in the input), then the `||` "or" clause outputs the required message. Otherwise the `grep .` matches all lines output from `comm`.

Try it online.
> 4 votes

# Answer
# Python 2,~~104,93,130~~,114 bytes

```
r=input()
print' '.join(n+x for n in list('23456789JQKA')+['10']for x in'HDSC'if n+x not in r)or'No missing cards'

```

Try it online!

* -10 bytes with hardcoding the list instead of using range!
* +37 bytes - missed printing 'No missing cards' if all cards are present in input!
* -16 bytes by modifying the code into a list comprehension!
> 4 votes

# Answer
# Ruby, 108 + 1 = 109 bytes

Uses the `-p` flag.

```
a=[*?2..'10',?J,?Q,?K,?A].map{|i|%w"H D S C".map{|c|i+c}}.flatten-$_.split;$_=a==[]?"No missing cards":a*' '

```
> 2 votes

# Answer
# PHP, 143 Bytes

```
foreach([H,D,S,C]as$c)foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$v)$r[]=$v.$c;echo join(" ",array_diff($r,explode(" ",$argn)))?:"No missing cards";

```
> 2 votes

# Answer
# sed, 157 + 1 (`-r` flag) = ~~170~~ 158 bytes

```
x
s/$/;A2345678910JQK/
s/.+/&H&D&S&C;No missing cards/
:
s/(10|\w)(\w+)(.);/\1\3 \2\3;/
t
G
:s
s/(10.|[^ ;1]{2})(.*\n.*)\1/\2/
ts
s/[ ;]+/ /g
s/^ //
s/ N.+//

```

Try it online!

This generates all possible cards and then remove each card in the input from the generated cards.
> 2 votes

# Answer
## JavaScript (ES6), ~~117~~ ~~114~~ 111 bytes

```
s=>[...Array(52)].map((_,i)=>~s.search(c=('JQKA'[v=i>>2]||v-2)+'CDHS'[i&3])?_:c+' ').join``||'No missing cards'

```

This takes advantage of the fact that *undefined* entries in the array generated by `map()` are coerced to empty strings when `join()`'d.

### Demo

```
let f =

s=>[...Array(52)].map((_,i)=>~s.search(c=('JQKA'[v=i>>2]||v-2)+'CDHS'[i&3])?_:c+' ').join``||'No missing cards'

console.log(f('9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S'))
```
> 2 votes

# Answer
## C#, 282 bytes

---

**Golfed**

```
i=>{var o=new System.Collections.Generic.List<string>();string[] S={"H","D","S","C"},N="A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');foreach(var s in S){foreach(var n in N){if(!System.Linq.Enumerable.Contains(i,n+s)){o.Add(n+s);}}}return o.Count>0?string.Join(" ",o):"No missing cards";};

```

---

**Ungolfed**

```
i => {
    var o = new System.Collections.Generic.List<string>();
    string[] S = { "H", "D", "S", "C" }, N = "A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');

    foreach( var s in S ) {
        foreach( var n in N ) {
            if( !System.Linq.Enumerable.Contains( i, n + s ) ) {
                o.Add( n + s );
            }
        }
    }

    return o.Count > 0
        ? string.Join( " ", o )
        : "No missing cards";
};

```

---

**Ungolfed readable**

```
i => {
    // Initialize a list to contain the list of cards missing
    var o = new System.Collections.Generic.List<string>();

    // Initialize the list of suits and numbers of cards
    string[] S = { "H", "D", "S", "C" }, N = "A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');

    // Cycle through the suits...
    foreach( var s in S ) {
        // ... and the numbers ...
        foreach( var n in N ) {
            // ... and check it the combo number + suite is missing
            if( !System.Linq.Enumerable.Contains( i, n + s ) ) {
                // If it's missing, add it to the list of missing cards
                o.Add( n + s );
            }
        }
    }

    // If the count of missing cards is greater than 0...
    return o.Count > 0
        // Build a 'space' separated string with the missing cards
        ? string.Join( " ", o )
        // Or output the missing cards string
        : "No missing cards";
};

```

---

**Full code**

```
using System;
using System.Collections.Generic;
using System.Linq;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, Int32> f = i => {
            var o = new List<string>();
            string[] S = { "H", "D", "S", "C" }, N = "A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');

            foreach( var s in S ) {
               foreach( var n in N ) {
                  if( !i.Contains( n + s ) ) {
                     o.Add( n + s );
                  }
               }
            }

            return o.Count > 0
               ? string.Join( " ", o )
               : "No missing cards";
         };

         List<String>
            testCases = new List<String>() {
                "9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S"
            };

         foreach( String testCase in testCases ) {
            Console.WriteLine( $"{test}\n{f( test.Split( ' ' ) )}" );
         }

         Console.ReadLine();
      }
   }
}

```

---

**Releases**

* **v1.0** \- `282 bytes` \- Initial solution.

---

**Notes**

Nothing to add
> 2 votes

# Answer
# Retina, 76 bytes

```
^
A2345678910JQK¶
\G(10|.)
 $&H $&D $&S $&C
Dr` \S+
G1`
^$
No missing cards

```

Input/output is a list of space-separated cards. Output has a leading space.

Try it online!

### Explanation

Most of the code deals with building the full list of cards that should be in the deck:

```
^
A2345678910JQK¶
\G(10|.)
 $&H $&D $&S $&C

```

First, we prepend a newline to the input, with all possible values of cards, then for each character of this line (or the couple of characters `10`) we build the list of all possible suits of that card.

```
Dr` \S+

```

This is a deduplication stage, it splits the string into chunks consisting of a space plus some non-spaces and keeps only one occurrence of each chunk. The modifier `r` makes this operate from right to left, keeping then the *last* occurrence of each chunk.

```
G1`

```

We keep only the first line, which now contains the missing cards.

```
^$
No missing cards

```

If the result is empty we replace it with "No missing cards"
> 2 votes

# Answer
# Python 3, 106 bytes

Combination of the two previous python answers mixed with some string unpacking shenanigans.

```
print(' '.join({x+y for x in[*'23456789JQKA','10']for y in'HDSC'}-{*input().split()})or'No missing cards')

```
> 1 votes

# Answer
# Julia, 116 bytes

```
print(join(setdiff(["$x$y"for x=∪(2:10,"JQKA")for y="HDSC"],readline()|>split),' ')|>s->s>""?s:"No missing cards")

```

Try it online!

Very similar to Kyle Gullions python solution. Setdiff instead of - and the lambda to test for the empty string make it worse though.
> 1 votes

# Answer
# Japt, 39 bytes

```
"JQKA"¬c9õÄ)ï+"CHSD"q)kU ¸ª`No ÚÍg Ößs

```

Try it
> 1 votes

# Answer
# Tcl, 270 228 chars

(Shortened with some help from Wît Wisarhd)

```
foreach s {H D S C} {foreach c {2 3 4 5 6 7 8 9 J Q K A} {dict set d $c$s 0}}
gets stdin l
foreach c $l {dict set d $c 1}
set m {}
dict for {c h} $d {if {!$h} {lappend m $c}}
if {![llength $m]} {set m "No missing cards"}
puts $m

```

Try it online!

Explanation:

This implementation builds a dictionary consisting of a boolean flag for each of the cards represented by the cartesian product of H D S C and 2-through-A. It reads the line from stdin, which if given as the spec as called for, is actually a well formed Tcl list. As each card is read, a boolean true is input in the dictionary for that card.

At the end a parser loops through the dictionary, and adds any card that did not have a true in the dictionary to a list of missing cards. If the missing cards list length is zero, output "No missing cards", otherwise output the list of missing cards.
> 1 votes

# Answer
# PHP, 138 bytes

Ran with `-n` and `-d error_reporting=0`

I reuse some code from an old submition i made that asked for create a deck of cards

**Code**

```
<?$r=[];foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)array_push($r,$t.H,$t.S,$t.D,$t.C);
echo join(" ", array_diff($r,explode(" ",$argv[1])));

```

Try it online!

**Explanation**

```
<?$r=[];   # Declare the array that will contain the full deck
# the next line will generate the arry with the full deck
foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)array_push($r,$t.H,$t.S,$t.D,$t.C);
# explode the input string on each blank space and using array_diff to get the
# different elements withing both arrays. (and "echo" of course)
echo join(" ", array_diff($r,explode(" ",$argv[1])));

```
> 1 votes

# Answer
# C# (.NET Core), 197 bytes

Without LINQ.

```
s=>{var w="";for(var j=0;j<52;){var u="";int t=j%13;u=t<1?"K":t<2?"A":t<11?t+"":t<12?"J":"Q";t=j++/13;u+=t<1?"H":t<2?"D":t<3?"S":"C";w+=s.IndexOf(u)<0?u+" ":"";}return w==""?"No missing cards":w;};

```

Try it online!
> 1 votes

# Answer
# Perl 6, 73 bytes

```
put keys((<<{^9+2}J Q K A>>X~ <C S D H>)∖get.words)||"No missing cards"

```

Try it online!

Some pretty simple set subtraction between the deck of cards and the input.
> 1 votes

# Answer
# Python 3, 102 bytes

```
lambda s:' '.join(i+j for i in[*'A23456789JQK','10']for j in'HDSC'if(i+j)not in s)or'No missing cards'

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Nested lists as printable 2D objects

text:
# Question
Title: Nested lists as printable 2D objects
I don't know if something like this exists already (and I'm not finding the right key words) but if not, it felt like it could be an interesting coding puzzle.

The challenge is, to take an arbitrarily nested list (no more than 2 deep), and display the content in a terminal in 2 dimensions in a 'pretty' manner. Each 'top level' dictionary element should read left - right, and the nested content for each top level index should be displayed vertically in line with its index position.

### Example input:

```
[["A"], ["B", "C"], ["D"], ["E", "F", "G"], ["H"]]

```

### Expected output (option 1):

```
 A B D E H
   C   F
       G

```

### Expected output (option 2):

In this case, 'stacks' should be as close to centralised as possible, so there is a similar amount of content above and below the top level left-to-right content.

```
       E
 A B D F H
   C   G

```

### Example input 2

List contents (for the purpose of this challenge) can be any length, but will always be the *same* length. e.g.

```
[["ABC"], ["BCD", "CDE"], ["DEF"], ["EFG", "FGH", "GHI"], ["HIJ"]]

```

Would also be valid, and should be rendered in similar fashion to example 1:

```
                                             EFG
ABC BCD DEF EFG HIJ      or      ABC BCD DEF FGH HIJ
    CDE     FGH                      CDE     GHI
            GHI

```

Other input considerations (updated in response to comments):

* The indexes of the top level, and nested lists will never be empty.

Criteria:

* The solution should take a list of lists (nested 1 deep).
* The format of the output is flexible, but it should be clear which elements of the list are distinct at the top level (left to right, in my example separated by spaces) and which elements of the sublists are which (top to bottom, separated vertically on successive lines in my example).
* Each item in a sublist inside the list should be printed aligned with each other in the vertical direction.
* I don't care about speed/complexity/byte count, so at the highest level the criteria will be considered met by any code that can produces the desired 2D output. The winner is therefore a `popularity-contest`, in that most votes wins (edit: now that answers have started being added the winner will be the answer with the most votes 1 week from today, but new answers would always be welcome).

Bonus points:

* How 'pretty' the output is, I'll leave to you. Whether you want it to 'cascade' from the top most character as example 1, or a pseudo-centrally aligned output as example 2. Any other creative solutions are also welcomed.
* Code which can handle variable length strings in any position.

---

I'm particularly interested in Python solutions, but anything goes.

# Answer
> 2 votes
# JavaScript (Node.js), 112 107 105 bytes

-1 byte thanks to @Kevin

Despite the controversy in the comments, I gave it a shot. It's my first ever codegolf submission and I had a lot of fun making it.

Tips & tricks are more than welcome!

```
a=>{o=['','',''];for(b of a)for(c=3;c--;)o[c]+=(b[c]?b[c]:' '.repeat(b[0].length))+' ';return o.join`\n`}

```

Try it online!

# Answer
> 2 votes
# 05AB1E

Since this is a , I wasn't entirely sure how to answer (might have been best to not answer at all, but I figured I'd gave it a shot anyway). I've added two answers below: one submission I would normally post and one 'pretty output' submission with multiple options (which isn't golfed whatsoever, might do so as well later on). *If the rules have been clarified I will update (or delete) accordingly.*

### Code-golf submission (7 bytes):

```
ннgð×ζ»

```

(Based on the current test cases, so assumes all string items are of the same length.)
Outputs in a similar matter as the first examples in the test cases of the challenge description.

Try it online or verify all test cases.

**Explanation:**

```
н        # Take the first inner list of the (implicit) input
         #  i.e. [["ABC"],["BCD","CDE"],["DEF"],["EFG","FGH","GHI"],["HIJ"]] → ["ABC"]
 н       # Pop and take the first string of that
         #  i.e. ["ABC"] → "ABC"
  g      # Pop and get it's length
         #  i.e. "ABC" → 3
   ð×    # Push a space character " " and increase it to that size
         #  i.e. 3 → "   "
     ζ   # Zip/transpose (swapping rows/columns) of the (implicit) input,
         # with the spaces-string as filler
         #  i.e. [["ABC"],["BCD","CDE"],["DEF"],["EFG","FGH","GHI"],["HIJ"]] and "   "
         #   → [["ABC","BCD","DEF","EFG","HIJ"],["   ","CDE","   ","FGH","   "],["   ","   ","   ","GHI","   "]]
      »  # Join by newlines (which implicitly joins inner lists by spaces)
         #  → "ABC BCD DEF EFG HIJ\n    CDE     FGH    \n            GHI    "
         # (and output the result implicitly)

```

---

### 'Pretty output' submission with options:

Here we take an additional integer input as input, and 'pretty print' the output based on the option:

```
1: ABC BCD DEF EFG HIJ
       CDE     FGH
               GHI

2:             GHI
       CDE     FGH
   ABC BCD DEF EFG HIJ

3:             EFG
   ABC CDE DEF FGH HIJ
       BCD     GHI

4:     CDE     EFG
   ABC     DEF FGH HIJ
       BCD     GHI

```

As for the code (it's not golfed or properly tested whatsoever, as can be seen quite easily XD):

```
i
 ннgð×ζ»
ë¹<i
 ннgð×ζR»
ë¹Íi
 ннgð×ζøε2ä}DεθR}ø»,€нø»,
ë¹4Qi
 ннgð×©ζøεD®¢._}ø»
ë
 ¹"Option ÿ is not available."

```

Try it online or see all options in action.

# Answer
> 2 votes
# Golfed - Jelly, 4 bytes

```
z“”G

```

Try it online!

# Pretty Printing with boxes - Python 3, 656 bytes

```
def f(matrix):
	length = max(map(len, matrix))
	lengths = []
	for index in range(len(matrix)):
		matrix[index] = ([""] * -((len(matrix[index]) - length) // 2) + matrix[index] + ([""] * ((length - len(matrix[index])) // 2)))
		hlength = max(map(len, matrix[index]))
		lengths.append(hlength)
		matrix[index] = [item.ljust(hlength) for item in matrix[index]]
	horiz = ["─" * e for e in lengths]
	print("┬".join(horiz).join("┌┐"))
	for row in list(zip(*matrix))[:-1]:
		print("│".join(row).join("││"))
		print("┼".join(horiz).join("├┤"))
	print("│".join(col[-1] for col in matrix).join("││"))
	print("┴".join(horiz).join("└┘"))

```

Try it online!

# Pretty Printing original (even spacing) - Python 3, 371 bytes

```
def f(matrix):
	length = max(map(len, matrix))
	for index in range(len(matrix)):
		matrix[index] = ([""] * -((len(matrix[index]) - length) // 2) + matrix[index] + ([""] * ((length - len(matrix[index])) // 2)))
		hlength = max(map(len, matrix[index]))
		matrix[index] = [item.ljust(hlength) for item in matrix[index]]
	for row in list(zip(*matrix)):
		print(" ".join(row))

```

Try it online!

# Answer
> 1 votes
# PHP, ~~162~~ 160 bytes

Even though this isn't code-golf, here's the golfed version anyway:

```
function($t){$r=0;while($b=array_column($t,$r,0)){if($r++==$y=0)$a=$b;foreach($a as$k=>$x)printf("% -".max(array_map('strlen',$t[$y++]))."s ",$b[$k]);echo"
";}}

```

Try it online!

And ungolfed:

```
function nested( $t ) {
	$r = 0;
	while ( $b = array_column( $t, $r, 0 ) ) {
		if ( $r++ === 0 ) $a = $b;
		$y = 0;
		foreach( $a as $k => $x ) {
			$l = max( array_map('strlen', $t[$y++] ) );
			printf( "% -". $l ."s ", $b[$k] );
		}
		echo "\n";
	}
}

```

Tests:

```
[["A"], ["B", "C"], ["D"], ["E", "F", "G"], ["H"]],
[["A"], ["B2", "C"], ["D"], ["E", "FGH", "G"], ["H"]],
[["ABC"], ["BCD", "CDE"], ["DEF"], ["EFG", "FGH", "GHI"], ["HIJ"]],
[["ABC"], ["BCD", "CDEF"], ["DEF"], ["EFG", "FGH", "GHIII"], ["HIJK"]],
[["ABC123","FOO","BCD", "CDEF","BAR"], ["BCD", "PPCG_RULEZ"], ["DEF"], ["EFG", "FGH", "GHIII","BCD", "CDE"], ["HIJK"]]

```

This will line up columns for strings of any length. Also, any number of rows will display fine too.

Output:

```
A B D E H
  C   F
      G

A B2 D E   H
  C    FGH
       G

ABC BCD DEF EFG HIJ
    CDE     FGH
            GHI

ABC BCD  DEF EFG   HIJK
    CDEF     FGH
             GHIII

ABC123 BCD        DEF EFG   HIJK
FOO    PPCG_RULEZ     FGH
BCD                   GHIII
CDEF                  BCD
BAR                   CDE

```

# Answer
> 0 votes
## Python 3, 153 chars

Tried desperately to get this to work with a list comprehension, but here is my attempt.

```
l=len;p=print
for j in range(l(max(x,key=l))):
  for i in range(l(x)):
    if(l(x[i])>j):p(x[i][j],end=' ')
    else:p(' '*l(x[i][0]),end=' ')
  p()

```

# Answer
> 0 votes
# C# (.NET Core), 205 bytes

Without LINQ.

Takes in a jagged array and prints the junk out.

```
p=>{var i=p.Length;int q,j=0;for(q=0;q<i;q++){var z=p[q].Length;j=z>j?z:j;}var s="";for(q=0;q<j;q++){for(var k=0;k<i;){try{s+=p[k++][q]+" ";}catch{s+=new string(' ',p[0][0].Length+1);}}s+="\n";}return s;};

```

Try it online!

---
Tags: array, popularity-contest
---