# Question
Title: Tell my friends to which "comma club" they belong
Inspired by Silicon Valley's "three-comma club" scenes, like this one, in this challenge you'll be telling ten people the "comma club" to which they each belong.

If you're unfamiliar with the term "comma club," let me explain: you're in the one-comma club if the money you have is in the inclusive range $1,000.00 to $999,999.99; you're in the two-comma club if it's in the range $1,000,000.00 to $999,999,999.99; these "clubs" repeat through the three-comma club, since no individual on Earth (AFAIK) owns more than one trillion U.S. dollars (Japanese Yen would be a different story very quickly). So, the number of commas your bank account has, according to the notation standards most common in the United States and Great Britain, denotes the comma club to which you belong. The same "comma" rules apply for negative numbers (although you wouldn't want to be in the negative comma club): negative amounts in the inclusive range \[-0.01, -999.99\] belong to the zero-comma club, amounts in the range \[-1000.00, -999999.99\] belong to the one-comma club, etc.

# The test cases

```
Friend    Amount
John      100000
Jamie     0.05
Kylie     1549001.10
Laura     999999999.99
Russ      986000000
Karla     1
Reid      99.99
Mark      999.99
Manson    1000.01
Lonnie    999999999999.00
Nelly     -123.45

```

The right answers:

```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

```

Whatever array setup you need to get a `friends` array and `amounts` array does not count towards your score. So for Python, the following code doesn't count:

```
f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = ['100000', '0.05', '1549001.10', '999999999.99', '986000000', '1', '99.99', '999.99', '1000.01', '999999999999.00']

```

### Edit: Please see the revised test cases

I removed the actual string commas from the test cases to make things a bit more difficult, as opposed to just counting commas.

# Answer
## JavaScript (ES6), 80 bytes

```
a=>a.map(([s,n])=>s+` is in the ${n.toFixed(n<0?3:4).length/3-2|0}-comma club.`)

```

Takes an array of \[friend, amount\] arrays and returns an array of "friend is in the n-comma club." strings. Works by adding extra trailing zeros so that the length is 6-8 for the 0-comma club, 9-11 for the 1-comma club, 12-15 for the 2-comma club etc.

https://jsfiddle.net/cau40vmk/1/
> 10 votes

# Answer
# PostgreSQL, 61 bytes

```
SELECT f||' is in the '||div(log(@a),3)||'-comma club.'FROM p

```

`@x` is the absolute value of `x`, `log(x)` is base-10 logarithm and `div(y, x)` computes the integer quotient of y/x.

---

Setup:

```
CREATE TEMP TABLE p AS
SELECT * FROM (VALUES
    ('John', 100000),
    ('Jamie', 0.05),
    ('Kylie', 1549001.10),
    ('Laura', 999999999.99),
    ('Russ', 986000000),
    ('Karla', 1),
    ('Reid', 99.99),
    ('Mark', 999.99),
    ('Manson', 1000.01),
    ('Lonnie', 999999999999.00),
    ('Nelly', -123.45)
) AS p (f, a)

```

---

Output:

```
            ?column?
--------------------------------
 John is in the 1-comma club.
 Jamie is in the 0-comma club.
 Kylie is in the 2-comma club.
 Laura is in the 2-comma club.
 Russ is in the 2-comma club.
 Karla is in the 0-comma club.
 Reid is in the 0-comma club.
 Mark is in the 0-comma club.
 Manson is in the 1-comma club.
 Lonnie is in the 3-comma club.
 Nelly is in the 0-comma club.
(11 rows)

```
> 10 votes

# Answer
# Jelly, ~~34 32~~  31 bytes

```
AḞbȷL’⁶;“£ṙƬs⁾`¬ụṂ“¢<ỴȦ8£l»j)⁹żY

```

A dyadic link (function) which takes a list of bank balances as numbers (decimals / integers) and a list of names as strings and returns a list of strings.

**Try it online!** \- the footer `çY`simply calls the function and joins the resulting list with line feeds so it has nice output when run as a full program.

### How?

```
AḞbȷL’⁶;“£ṙƬs⁾`¬ụṂ“¢<ỴȦ8£l»j)⁹ż - Main link: bankBalances, names
                            )   - for each bankBalance:
A                               -   absolute value (treat negatives and positives the same)
 Ḟ                              -   floor (get rid of any pennies)
  bȷ                            -   convert to base 1000
    L                           -   length (number of digits in base 1000)
     ’                          -   decrement by one
      ⁶;                        -   concatenate a space with that   ...because -------.
        “         “       »     -   compressed list of strings:                       ↓
         £ṙƬs⁾`¬ụṂ              -     " is in the"  ← cannot compress a trailing space :(
                   ¢<ỴȦ8£l      -     "-comma club."
                           j    -   join that list of strings with the "number plus space"
                             ⁹  - right argument (names)
                              ż - zip with L

```
> 7 votes

# Answer
# PHP, ~~76~~ 74 bytes

```
// data as associative array
$d=[Poorman=>-1234,John=>100000,Jamie=>0.05,Kylie=>1549001.10,Laura=>999999999.99,Russ=>1000000000,Karla=>1,Reid=>99.99,Mark=>999.99,Manson=>1000.01,Lonnie=>999999999999.00];
// code
foreach($d as$n=>$a)printf("$n is in the %d-comma club.
",log($a*$a,1e6));

```

Fortunately I don´t have to cast to int (as I would have to in C); PHP does that implicitly for `%d`.
> 4 votes

# Answer
# Japt, 36 bytes

This takes in the amount as the first input, name as the second.

```
V+`   e {w0 x4 l /3-2|0}-¬mµ club

```

### Explanation

```
V+`   e {w0 x4 l /3-2|0}-¬mµ club
V+                                   // Second input +
  `                                  // compressed string:
      e                              // " is in the "
        {              }             // Insert here:
         w0                          //   The larger of 0 and the first input
            x4                       //   Rounded to the 4th decimal
               l                     //   Length
                        -¬mµ club    // "-comma club"
                                     // A closing backtick is auto-inserted at the end of the program

```

Japt uses the shoco library for string compression.

*Inspired by @Neil's solution.*

*Saved 7 bytes thanks to @ETHproductions*

Try it online!
> 4 votes

# Answer
# Mathematica (86 bytes)

The set-up (with names as strings, money as numbers):

```
n = {"John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"};
m = {100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45}

```

The attempt:

```
MapThread[#~~" is in the "~~ToString@Max[Floor@Log[10^3,#2],0]~~"-comma club."&,{n,m}]

```

All of Mathematica's string functions include "String" in the name, so I think logs are shorter. The `Max[...,0]` is to deal with the pesky negative numbers or negative infinity for people who own between -1 and 1 dollars. The log of a negative number includes imaginary stuff, but Mathematica helpfully ignores that when taking a `Floor`!
> 4 votes

# Answer
# MATL, ~~50~~ ~~48~~ 43 bytes

```
`j' is in the 'i|kVn3/XkqV'-comma club'&hDT

```

Try it at **MATL Online**

**Explanation**

```
`                   % Do...While loop
  j                 % Explicitly grab the next input as a string
  ' is in the the ' % Push this string literal to the stack
  i                 % Grab the next input as a number
  |                 % Compute the absolute value
  k                 % Round towards zero
  V                 % Convert to a string
  n3/Xk             % Divide the length of the string by 3 and round up
  q                 % Subtract one
  V                 % Convert to a string
  '-comma club'     % Push this string literal to the stack
  &h                % Horizontally concatenate the entire stack
  D                 % Display the resulting string
  T                 % Push TRUE to the stack, causing an infinite loop which automatically
                    % terminates when we run out of inputs
                    % Implicit end of do...while loop

```
> 3 votes

# Answer
# 05AB1E, 32 bytes

```
Äï€g3/î<“-comma†Ú“«“€ˆ€†€€ “ì‚ø»

```

Try it online!

**Explanation**

```
Ä                                 # absolute value of input
 ï                                # convert to int
  €g                              # length of each
    3/                            # divided by 3
      î                           # round up
       <                          # decrement
        “-comma†Ú“«               # append string "-comma club" to each number
                   “€ˆ€†€€ “ì     # prepend string "is in the " to each number
                             ‚    # pair with second input
                              ø   # zip
                               »  # join by spaces and newlines

```
> 3 votes

# Answer
# R, 68 bytes

The setup:

```
f <- c('John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie', 'Nelly')
a <- c(100000, 0.05, 1549001.10, 999999999.99, 986000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45)

```

The solution:

```
cat(paste0(f, " is in the ",floor(log10(abs(a))/3)),"-comma club.\n"))

```

Take the base 10 log of the absolute value of the account, round down then print with the names.

I'm not sure if it could be smaller if `a` would be a character vector...
> 3 votes

# Answer
## JavaScript, 59 bytes

*Saved 3 bytes thanks to @ETHproductions*

*Saved 2 bytes thanks to @Cyoce*

```
n=>m=>n+` is in the ${m>1?Math.log10(m)/3|0:0}-comma club.`

```

### Demo

```
f=n=>m=>n+` is in the ${m>1?Math.log10(m)/3|0:0}-comma club.`

console.log((f("John")(100000)))
console.log((f("Jamie")(0.05)))
console.log((f("Kylie")(1549001.10)))
console.log((f("Laura")(999999999.99)))
console.log((f("Russ")(986000000)))
console.log((f("Karla")(1)))
console.log((f("Reid")(99.99)))
console.log((f("Mark")(999.99)))
console.log((f("Manson")(1000.01)))
console.log((f("Lonnie")(999999999999.00)))
console.log((f("Nelly")(-123.45)))
```
> 3 votes

# Answer
# Python 3 (~~207 159 110 95~~ 86 bytes, thanks to @iwaseatenbyagrue)

A little bit of setup:

```
f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie', 'Nelly']
a = [100000, 0.05, 1549001.10, 999999999.99, 986000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45]

```

My attempt:

```
['%s is in the %d-comma club.'%(p,-(-len(str(int(abs(v))))//3)-1) for p,v in zip(f,a)]

```

Results:

```
['John is in the 1-comma club.', 'Jamie is in the 0-comma club.', 'Kylie is in the 2-comma club.', 'Laura is in the 2-comma club.', 'Russ is in the 2-comma club.', 'Karla is in the 0-comma club.', 'Reid is in the 0-comma club.', 'Mark is in the 0-comma club.', 'Manson is in the 1-comma club.', 'Lonnie is in the 3-comma club.', 'Nelly is in the 0-comma club.']

```

Edit: converting everything to absolute values saved me 15 bytes.
> 2 votes

# Answer
# Python 2.7, ~~89 86 84~~ 76 bytes

```
for g,b in input():print g,'is in the',`~-len('%d'%abs(b))/3`+'-comma club.'

```

**Try it online!**

Full program that takes a list of pairs of names and bank balances - and prints the resulting strings. (Note the question states "friends array and amounts array, but this is the format used by the accepted answer, so I guess it's allowed!)
> 2 votes

# Answer
# Vim, 72 bytes

```
:%s;\v +\-=(\d+).*;\=' is in the '.(len(submatch(1))-1)/3.' comma club'

```

Somehow I should show that there's a trailing return, but unsure how. This is just a basic regex answer, that I'm sure could be beaten by any regex language. I would have used V, but I think that the substitute commands in V use `/` as a separator by default, and I couldn't figure out how to make it not complain about the divide.

Takes input as OP's table, and returns values as the table, but with the financial information replaced by " is in the X comma club"

Try it online!
> 2 votes

# Answer
# Python 2, 69 bytes

Setup our arrays:

```
n = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = [100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00]

```

And our function can then be:

```
f=lambda n,a:'%s is in %s comma club'%(n,min(3,(len(str(int(a)))/3)))

```

Giving us:

```
>>> [f(x,y) for x,y in zip(n,a)]
['John is in 2 comma club', 'Jamie is in 0 comma club', 'Kylie is in 2 comma club', 'Laura is in 3 comma club', 'Russ is in 3 comma club', 'Karla is in 0 comma club', 'Reid is in 0 comma club', 'Mark is in 1 comma club', 'Manson is in 1 comma club', 'Lonnie is in 3 comma club']

```

If the array needs to be identical to that provided in the question, then the solution costs 76 bytes:

```
f=lambda n,a:'%s is in %s comma club'%(n,min(3,(len(str(int(float(a))))/3)))

```
> 2 votes

# Answer
## Powershell, 82 bytes

```
$args[0]|%{$_[0]+" is in the "+(('{0:N}'-f$_[1]-split',').Count-1)+"-comma club."}

```

Assuming a 2D-array input of

`cc.ps1 @(@("John",100000),@("Jamie",0.05),@("Kylie",1549001.10),@("Laura",999999999.99),@("Russ",986000000),@("Karla",1),@("Reid",99.99),@("Mark",999.99),@("Manson",1000.01),@("Lonnie",999999999999.00),@("Nelly",-123.45))`

The output is `John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.`
> 2 votes

# Answer
## Haskell, 71 bytes

```
n#a=n++" is in the "++(show.truncate.logBase 1e3.abs$a)++"-comma club."

```

Defines an operator '#' that provides the correct answer. E.g.:

```
*Main> "John"#100000
"John is in the 1-comma club."

```

Unfortunately, Haskell doesn't have a compact `log10` function like many other languages, but it does have a useful `logBase` function, which means we don't need to divide our answer by 3. Unfortunately, `logBase 1000 0.05` is a negative number, so we need to use the longer `truncate` rather than `floor` to round it.

Full program including test cases:

```
(#) :: (RealFrac n, Floating n) => [Char] -> n -> [Char]
n#a=n++" is in the "++(show.truncate.logBase 1e3.abs$a)++"-comma club."

testCases = [
 ("John",      100000),
 ("Jamie",     0.05),
 ("Kylie",     1549001.10),
 ("Laura",     999999999.99),
 ("Russ",      986000000),
 ("Karla",     1),
 ("Reid",      99.99),
 ("Mark",      999.99),
 ("Manson",    1000.01),
 ("Lonnie",    999999999999.00),
 ("Nelly",     -123.45)]

main = putStrLn $ unlines $ map (uncurry (#)) testCases

```

Gives the following results:

```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

```
> 2 votes

# Answer
## K, 66 bytes

```
    /n is names and a is amounts
    n
    ("John";"Jamie";"Kylie";"Laura";"Russ";"Karla";"Reid";"Mark";"Manson";"Lonnie")
    a
    ("100000";"0.05";"1549001.10";"999999999.99";"1000000000";,"1";"99.99";"999.99";"1000.01";"999999999999.00")
    /the function
    {x," is in the ",($(#.q.cut[3;*"."\:y])-1)," comma club"}./:+(n;a)
    /output
    ("John is in the 1 comma club";"Jamie is in the 0 comma club";"Kylie is in the 2 comma club";"Laura is in the 2 comma club";"Russ is in the 3 comma club";"Karla is in the 0 comma club";"Reid is in the 0 comma club";"Mark is in the 0 comma club";"Manson is in the 1 comma club";"Lonnie is in the 3 comma club")

```
> 1 votes

# Answer
# C#, 125 bytes

```
(p,n)=>{for(int x=0;x<p.Length;x++)Console.Write(p[x]+" is in the "+(n[x]<1e3?0:n[x]<1e6?1:n[x]<1e9?2:3)+"-comma club.\n");};

```

Anonymous function which prints the result in the the OP's format.

Full program with test cases:

```
using System;

class CommaClub
{
    static void Main()
    {
        Action<string[], double[]> f =
        (p,n)=>{for(int x=0;x<p.Length;x++)Console.Write(p[x]+" is in the "+(n[x]<1e3?0:n[x]<1e6?1:n[x]<1e9?2:3)+"-comma club.\n");};

        // test cases:
        string[] personArr = new[] {"John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"};
        double[] amountArr = new[] {100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45};
        f(personArr, amountArr);
    }
}

```
> 1 votes

# Answer
## Python 2, 87 bytes

```
for n,a in input():print n+' is in the %dd-comma club.'%'{:20,.2f}'.format(a).count(',')

```

Slightly older (90 bytes):

```
for n,a in input():print n+' is in the '+`'{:20,.2f}'.format(a).count(',')`+'-comma club.'

```

Takes input as a list of tuples (name, amount).

I'm doing this on my phone at school so I'll test it later.
> 1 votes

# Answer
# Perl 6, ~~107~~ 95 bytes

```
for @f {printf "%s is in the %d-comma club.\n",@f[$++],(abs(@a[$++].split(".")[0]).chars-1)/3;}

```

Not my proudest work, give me a heads up if ive forgotten any golfing techniques. EDIT: -12 bytes thanks to @Ven
> 1 votes

# Answer
# Swift, ~~166~~ ~~158~~ 145 bytes

```
var c="comma club",i=0
f.map{k,v in var a=abs(v);print(k,(1000..<1000000~=a ?1:1000000..<1000000000~=a ?2:1000000000..<1000000000000~=a ?3:0),c)}

```

And here is the dictionary:

```
var f = [
    "John": 100000, "Jamie": 0.05, "Kylie" : 1549001.10,
    "Laura": 999999999.99,"Russ":1000000000,"Karla": 1,
    "Reid": 99.99,"Mark": 999.99, "Manson": 1000.01,
    "Lonnie": 999999999999.00, "Nelly": -123.45
]

```

**Try it here!**
> 1 votes

# Answer
## dc, ~~56~~ 54 bytes

```
[P[ is in the ]Pd*vdZrX-1-3/n[-comma club.]pstz0<g]sglgx

```

This takes input from the stack, which should be pre-loaded with the first name at top of stack, the first number, the second name, second number, etc.

Here is an example of loading the stack and running the macro, g:

```
#!/usr/bin/dc
_123.45         [Nelly]
999999999999.00 [Lonnie]
1000.01         [Manson]
999.99          [Mark]
99.99           [Reid]
1               [Karla]
986000000       [Russ]
999999999.99    [Laura]
1549001.10      [Kylie]
0.05            [Jamie]
100000          [John]
[P[ is in the ]Pd*v1/Z1-3/n[-comma club.]pstz0<g]sglgx

```

which produces the usual output,

```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

```

Here's an exegesis of the code:

```
[P[ is in the ]Pd*v1/Z-1-3/n[-comma club.]pstz0<g]sglgx

[                    # begin macro string
P                    # print and pop person name
[ is in the ]P       # print and pop ' is in the '
# Get absolute value of number by squaring and square root
d*v                  # d=dup, *=multiply, v=root
1/                   # 1/ truncates to integer since scale is 0
Z                    # Z=number length
1-3/n                # n=print and pop (#digits - 1)//3
[-comma club.]p      # print '-comma club.' and newline
st                   # pop '-comma club.' off stack into register t
z0<g                 # Do macro g if 0 is less than z=stack height
]                    # end macro string
sg                   # Save macro g
lgx                  # Load g and do its initial execution

```

Note, in edit 1 I replaced `dZrX-` (d=dup, Z=number length, r=swap, X=fraction, -=subtract) with `1/Z` (divide number by 1, which with default scale of zero truncates to integer; then Z=number length), saving two bytes.
> 1 votes

# Answer
# JavaScript (V8), 55 bytes

```
n=>m=>n+` is in the ${Math.log10(m*m)/6|0}-comma club.`

```

Try it online!
> 1 votes

# Answer
# Vyxal, 29 bytes

```
¹ð«E⟨b?6Ḃ«⁰²∆τ6ḭS‹`ḊṄa ⟇¦.`Wṅ

```

Try it Online!

## Explained

```
¹ð«E⟨b?6Ḃ«⁰²∆τ6ḭS‹`ḊṄa ⟇¦.`Wṅ
¹ð                             # Get first input and push space
  «E⟨b?6Ḃ«                     # Push compressed string "is in the "
          ⁰²                   # Get second input and square it
            ∆τ                 # Log10 it
              6ḭ               # Floor divide by 6
                S              # Stringify
                 ‹             # Push a hyphen
                  `ḊṄa ⟇¦.`    # Push string "comma club"
                           Wṅ  # Join stack

```
> 1 votes

# Answer
# Java 8 ~~154~~ 141 bytes

```
m.keySet().stream().map(k->k+" is in the "+(((""+Math.abs(m.get(k).longValue()))).length()-1)/3+"-comma club.").forEach(System.out::println);

```

---

## Ungolfed

```
public static void main(String[] args) {
    Map<String, Number> m = new LinkedHashMap<String, Number>(){{
        put("John", 100000);
        put("Jamie", 0.05);
        put("Kylie", 1549001.10);
        put("Laura", 999999999.99);
        put("Russ", 1000000000);
        put("Karla", 1);
        put("Reid", 99.99);
        put("Mark", 999.99);
        put("Manson", 1000.01);
        put("Lonnie", 999999999999.00);
        put("Nelly", -123.45);
    }};
    m.keySet().stream().map(k->k+" is in the "+(((""+Math.abs(m.get(k).longValue()))).length()-1)/3+"-comma club.").forEach(System.out::println);
}

```
> 0 votes

# Answer
## Clojure, 108 bytes

```
(def f ["John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"])
(def a ["100000", "0.05", "1549001.10", "999999999.99", "986000000", "1", "99.99", "999.99", "1000.01", "999999999999.00", "-123.45"])

(map #(str %" is in the "(quot(-(count(nth(partition-by #{\.}(drop-while #{\-}%2))0))1)3)"-comma club.")f a)

```

Not sure if operating on floats would be shorted than on sequences of characters. Not sure if non-function answer is fine which returns a sequence of answers.
> 0 votes

# Answer
# Rebol, 118 bytes

```
d: charset"0123456789"forskip s 2[c: 0 parse s/2[opt"-"any[3 d and d(++ c)]]print[s/1"is in the"join c"-comma club."]]

```

Ungolfed with array declaration:

```
s: [
    {John} {100000}
    {Jamie} {0.05}
    {Kylie} {1549001.10}
    {Laura} {999999999.99}
    {Russ} {986000000}
    {Karla} {1}
    {Reid} {99.99}
    {Mark} {999.99}
    {Manson} {1000.01}
    {Lonnie} {999999999999.00}
    {Nelly} {-123.45}
    {Baz} {1.12345678}     ;; added extra Baz test case
]

d: charset "0123456789"
forskip s 2 [
    c: 0
    parse s/2 [
        opt "-"
        any [3 d and d (++ c)]
    ]
    print [s/1 "is in the" join c "-comma club."]
]

```

Output:

```
John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
Baz is in the 0-comma club.

```
> 0 votes

# Answer
# Factor, 52 bytes

```
[ sq log10 6 /i [I ${} is in the ${}-comma club.I] ]

```

Attempt This Online!

Port of @MatthewJensen's JavaScript answer.
> 0 votes

---
Tags: code-golf
---


title: Filthy and Unique

text:
# Question
Title: Filthy and Unique
In this question I will talk about programs as strings, this is strings of bytes, not characters. How your resultant program is rendered or displayed is not important to this challenge, only how it appears in memory matters.

A pristine program is a program \\$S\\$ that when run does not error, however it will error whenever a continuous substring of size \\$n\\$, where \\$1\leq n \< \left|S\right|\\$, is removed.

A filthy program is the opposite, it is a program \\$S\\$ that when run *does* error, however whenever a continuous substring of size \\$n\\$, where \\$1\leq n \< \left|S\right|\\$, is removed, it does not error.

For this challenge an error is non-empty output to STDERR.

Your challenge is to write a filthy program that uses as many unique bytes as possible. This means you will get one point for every unique byte that appears in your code with a larger score being better. The maximum score is thus 256.

# Answer
# Unary, 14 bytes

```
123456789ABCDE

```

This encodes the brainfuck program `[`, which errors due to unmatched brackets.

Removing bytes will result in `>`, `<`, `+`, `-`, `.`, `,` or the empty program, which are valid brainfuck programs.
> 21 votes

# Answer
# , 3 bytes

```
qrt

```

Try it online!

A name of an object is a valid program in R.

`qrt` is not the name of anything, so it returns an error.

`q` is the quit function

`qr` is the QR decomposition function

`rt` is the t distribution sampling function

`qt` is the t distribution inverse CDF

`t` is the transpose function
> 16 votes

# Answer
# Jelly, ~~4 5 6 7 8 10~~ 11 bytes

```
“a”;⁽PFð+µU

```

Try it online!

Verify it.

Tries to add a string with an integer.

Some of the possible subprograms:

`“a”` is a string literal.

`“a` is the same string literal.

is the empty string.

`“a”;` concatenates "a" with itself.

...too many to enumerate them all.
> 13 votes

# Answer
# Polyglot, 3 bytes

```
1 2

```

Works in:

* JavaScript
* Ruby
* R
* Octave
* GHCi
* Julia

In JavaScript, throws *SyntaxError: unexpected token: numeric literal* or a similar error.

All other strings are valid numeric literals (**1**, **2**, or **12**).

---

In GHCi this throws

```
<interactive>:1:1: error:
    • Non type-variable argument in the constraint: Num (t1 -> t2)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall t1 t2. (Num t1, Num (t1 -> t2)) => t2

```

This is because it tries to apply `1` to `2` as a function, however it cannot. When any part of this is removed it simply becomes a numeric literal.
> 7 votes

# Answer
# Python 2, 2 bytes

### Unexpected character after line continuation character

```
\0

```

`\` followed by any of `123456789 #`
Try it online!

### Invalid octal number

```
08

```

`0` followed by any of `89`
Try it online!

### Unexpected Indent

```
 0

```

or `\t` followed by any of `123456789\`
Try it online!
> 5 votes

# Answer
# Python 2/3, 3 bytes

```
4\f2

```

OR

```
4\x0c2

```

Try it online!

In python "\f" is the same as "\x0c" and is a form feed character. This means that it indicates for a printer to go to the next line.

If a python expression starts or ends with `\f`, it is basically ignored so `\f2` is a valid expression.

The `4` and `2` can be any number 0-9. However, for the first byte to be `0` is only valid in Python 2.7.15, as `02` was made a legal declaration of `2`.

So the expression itself fails with a Syntax Error, because there are two numbers separated by a whitespace. However, any shortening either puts `\f` at the beginning or end, where it doesn't matter, or it creates `42` which is valid.

(It is worth noting that in IDLE this file opens looking like "42".)

Form feed explanation source: https://stackoverflow.com/a/26184126
> 5 votes

# Answer
# Dyalog APL, 5 bytes (SBCS)

```
~≢0 1

```

Try it online! or test all the possible programs

There sure are better boring answers, but this is the best non-boring one I've found

SBCS is required as Dyalog Classic seems to always have output in STDERR, making it unusable.
> 4 votes

# Answer
# Zsh, 2 bytes

```
:#
```

Attempt This Online!

Zsh is very good at producing errors, so this challenge is very hard.

* `:` on its own is command which does nothing
* `#` is a comment
* `:#` is a single command, which doesn't exist, and therefore errors. (`#` is only a comment when it's at the start of a word)
> 1 votes

---
Tags: code-challenge, pristine-programming
---


title: Render "Digital Clock Style" Numbers

text:
# Question
Title: Render "Digital Clock Style" Numbers
Write the shortest program which will take a string of numbers (of up to *at least* 20 length) as input, and display the output using the standard digital clock style numbers. For instance for input 81, a solution with ascii output would give:

```
 _
|_|  |
|_|  |

```

Graphical output is also acceptable, if it helps.

# Answer
> 7 votes
## APL (Dyalog) (45)

```
{3 3⍴' _|'[1+⍵⊤⍨9⍴3]}¨⎕UCS'ા8धगɯે૙ࣃଏ૽'[1+⍎¨⍞]

```

The string, `ા8धगɯે૙ࣃଏ૽`, are the unicode characters `2750 56 2343 2327 623 2759 2777 2243 2831 2813` (however, you should be able to just copy and paste it). They encode the numbers. The program reads a line from the keyboard.

Explanation:

* `1+⍎¨⍞`: read a line from the keyboard, parse each character as a digit, then add 1 to each number (APL arrays are 1-based by default).
* `⎕UCS'ા8धगɯે૙ࣃଏ૽'[`...`]`: Select the characters belonging to the digits of the numbers you entered, and look up the Unicode values.
* `{`...: for each of these values, do:
* `1+⍵⊤⍨9⍴3`: get the first 9 base-3 digits from the value as expressed in base-3, and add 1 (because the arrays ar 1-based).
* `' _|'[`...`]`: select a space, horizontal line, or vertical line depending on these digits
* `3 3⍴`: format as a 3-by-3 box.

# Answer
> 44 votes
## Funciton

Not really a language suitable for golfing... but regardless, I tried to keep the code size as small as I could — quite a different challenge than in “usual” languages. This is **1555 characters** or **3110 bytes** (if encoded as UTF-16; UTF-8 is larger).

Here’s a screenshot of the program running. It really works:

Since this looks ugly in StackExchange due to the extra line spacing, consider running the following code in your browser’s JavaScript console to fix that: `$('pre').css('line-height',1)`

```
     ╓─╖ ╔╗┌─╖   ┌─╖
     ║ɧ║ ║╟┤↔╟┐ ┌┤‼╟┐
     ╙┬╜ ╚╝╘═╝│ │╘╤╝│
╔═╗  ┌┴────┐  │┌┴╖ ┌┴╖
║0║ ┌┴─┐  ┌┴─┐└┤ɧ╟─┤·╟┐
╚╤╝┌┴╖┌┴╖┌┴╖┌┴╖╘╤╝ ╘╤╝│
┌┘┌┤·╟┤ɦ╟┤·╟┤?╟ │  ┌┴╖│
│ │╘╤╝╘╤╝╘╤╝╘╤╝ └──┤‼╟┘
│┌┴╖│ ┌┴╖┌┘╔═╧╗    ╘═╝
└┤?╟┘┌┤?╟┘┌╢10║    ┌─────────┐
 ╘╤╝ │╘╤╝┌┘╚══╝ ┌─┬┘╔══╗┌──╖┌┴╖ ╓─╖
  ┘  └───┘╔════╗│┌┴┐║21╟┤>>╟┤·╟┐║ɦ║
╔════════╗║1005╟┘└┬┘╚══╝╘═╤╝╘╤╝│╙┬╜        ┌─┐
║14073768║╚════╝ ┌┴╖ ┌─╖ ┌┴╖┌┴╖└─┴─────────┘┌┴╖
║7584800 ╟───────┤?╟─┤‼╟─┤ɧ╟┤·╟─────────────┤·╟┐╔═══════╗╔══╗
╚════════╝       ╘╤╝ ╘╤╝ ╘╤╝╘╤╝    ╔══╗┌─╖┌┐╘╤╝│║2097151║║21╟┐
 ╔═══════════════╗│   ┘   │  │     ║48╟┤−╟┤├─┤┌┘╚══╤════╝╚══╝│
 ║140737555464224╟┘  ┌────┘┌┬┘     ╚══╝╘╤╝└┘┌┘│╓─╖ │┌┐┌─╖┌─╖┌┴─╖
 ╚═══════════════╝   │ ┌───┘└─────────┐┌┴─╖ │┌┘║↔║ ├┤├┤‼╟┤↔╟┤>>║
┌────────────┐┌────┐┌┴╖│┌────────────┐├┤<<║ ││ ╙┬╜┌┘└┘╘╤╝╘═╝╘╤═╝
│   ╔══╗╔═══╗├┘╓─╖ └┤·╟┘│   ╔══╗╔═══╗├┘╘╤═╝ │└─┐└─┤╔═╗┌┴╖ ┌──┘
│   ║95║║892║│┌╢‡╟┐ ╘╤╝ │   ║95║║877║│ ┌┘╔══╧═╗│  │║0╟┤?╟┬┘
│   ╚═╤╝╚═╤═╝││╙─╜│  │  │   ╚═╤╝╚═╤═╝│╔╧╗║2097║│  │╚═╝╘╤╝│
│╔══╗┌┴╖┌┐│  ││┌─╖│ ┌┴╖ │╔══╗┌┴╖┌┐│  │║1║║151 ║│  └──────┘
│║32╟┤?╟┤├┤  │└┤‼╟┘┌┤‡║ │║32╟┤?╟┤├┤  │╚═╝╚════╝│
│╚══╝╘╤╝└┘└──┴┐╘╤╝ │╘╤╝ │╚╤═╝╘╤╝└┘└──┴┐      ┌─┘
│    ┌┴╖     ┌┴╖┌─╖│ │ ┌┴╖│  ┌┴╖     ┌┴╖ ┌─╖┌┴╖
│    │‼╟─────┤·╟┤‼╟┘ │┌┤·╟┘  │‼╟─────┤·╟─┤‼╟┤‡║
└┐┌┐ ╘╤╝     ╘╤╝╘╤╝  ││╘╤╝┌┐ ╘╤╝     ╘╤╝ ╘╤╝╘╤╝
 ├┤├┐┌┴╖╔══╗  └──┐┌┐ │└┐├─┤├┐┌┴╖╔══╗  ├──┐└  │
 │└┘└┤?╟╢32║╔═══╗├┤│┌┴╖││ └┘└┤?╟╢32║╔═╧═╗│┌┐┌┴╖╔══╗
╔╧══╗╘╤╝╚══╝║881╟┘│├┤?╟┘│    ╘╤╝╚══╝║325║└┤├┤?╟╢32║
║927║╔╧══╗  ╚═══╝ └┘╘╤╝╔╧═══╗╔╧══╗  ╚═══╝ └┘╘╤╝╚══╝
╚═══╝║124╟───────────┘ ║1019║║124╟───────────┘
     ╚═══╝             ╚════╝╚═══╝

```

It could probably be smaller if I hadn’t made a mistake due to which the output was back to front; I fixed that by adding an extra function to reverse the input. Otherwise I would probably have to rewrite all of it.

I also made another mistake (swapping the operands in two calls to ) which made it necessary to declare the extra  function, but this one is so small it fits *inside* the main function and thus doesn’t add any characters!

# Answer
> 9 votes
## J, 90, 78 68 chars

\[ **update:** using unicode (1 byte) encoding:

```
,./(10 3 3$((90$3)#:256#.24x-~3&u:'%ė¨ÔW/~º»sy¡ăì<t÷²'){' _|'){~"./.Y
NB. utf characters are: 37 279 168 212 87 47 126 186 187 115 121 161 259 236 60 116 247 178

```

works as before: \]

```
,./(10 3 3$((90$3)#:1219424106940570763878862820444729939648410x){' _|'){~"./. '58321'
 _  _  _  _
|_ |_| _| _|  |
 _||_| _||_   |

```

The key is in the encoding of digits as base-3 integers. Zero, for example is:

```
:
 _
| |
|_|

```

or `' _ | ||_|'`, which becomes 0102022123 = 2750.

# Answer
> 9 votes
### wxpython, many characters

```
import wx, wx.gizmos as g

class T(wx.Frame):
 def __init__(_):
  wx.Frame.__init__(_, None, size = (800, 60))
  l = g.LEDNumberCtrl(_, -1)
  l.Value = raw_input()

class M(wx.App):
 def OnInit(_):
  T().Show()
  return 1

M().MainLoop()

```

Test

```
echo -n 81 | python codegolf-997-wx.py

```

ps: not a serious entry, but looks like graphical output is also acceptable, so I just gave it a try :-)

# Answer
> 8 votes
## Golfscript - 66 chars

```
"placeholder text for userscript which counts chars             ";

```

`xxd`: (use `xxd -r` to revert)

```
0000000: 332c 7b3a 533b 2e7b 3438 2d22 5e70 285d  3,{:S;.{48-"^p(]
0000010: 7025 d3c4 4ab1 7d4a b8dc 4469 ce41 2222  p%..J.}J..Di.A""
0000020: f303 227b 6261 7365 7d2f 3330 2f53 3d33  .."{base}/30/S=3
0000030: 2f3d 7b22 5f20 7c22 3d7d 257d 256e 407d  /={"_ |"=}%}%n@}
0000040: 2f3b                                     /;

```

This follows most of the other answers in that there are no spaces between numbers and trailing spaces are kept in. A space between numbers can easily be added with `1+` before `{"_ |"=}%`. Packed into a base 3 number, and then as base 243 into a string.

# Answer
> 5 votes
# Mathematica 205 209 198 179

```
i = IntegerDigits; t = Thread; r = Rule;
z@n_ := Row@i@n /. t[r[Range[0, 9], Grid[Partition[ReplacePart[Characters@" _ |_||_|",
t[r[#, ""]]], 3], Spacings -> 0] &
/@ (i /@ {5, 24578, 49, 47, 278, 67, 6, 4578, , 78})]]

```

**Usage**

```
z@1234567890

```

# Answer
> 5 votes
# JavaScript (145)

~~148~~ 145

Since JavaScript doesn’t really have standard input/output, this is written as a function that takes a string and returns the output as a string.

```
function r(n){for(i=o="",b=" |_\n|",L=n.length;i<3*L;)o+=b[(c="ǪĠòƲĸƚǚĢǺƺ".charCodeAt(n[i%L])>>(i++/L|0)*3)&1]+b[c&2]+b[c&4]+b[i%L?0:3];return o}

```

Spaced out:

```
function r(n)
{
    for (i = o = "", b = " |_\n|", L = n.length;   i < 3*L;   )
        o += b [ (c = "ǪĠòƲĸƚǚĢǺƺ".charCodeAt(n[i%L]) >> (i++/L|0)*3) & 1 ] +
             b [ c&2 ] +
             b [ c&4 ] +
             b [ i%L ? 0 : 3 ];  // space or newline
    return o
}

```

Here’s how it works:

* Every digit shape is encoded in a Unicode character consisting of 9 bits.
* The first three bits are for the first row, etc.
* In each group of three bits, the first specifies whether the first character is `|` or space, the second whether it’s `_` or space, and the third again `|` or space.
* These three bits are retrieved as `c&1`, `c&2` and `c&4`, which are then used as indexes into the string `b`.
* At each iteration, `i%L` is the “x-coordinate”, i.e. the digit within the input `n`
* At each iteration, `i/L` is the “y-coordinate”, i.e. the row, but we need `|0` to make it an integer
* Finally, the spaces between the digits and the newlines between the lines are *also* retrieved by indexing into `b`, re-using the space character *and* the otherwise unused position 3 in that string! :)

# Answer
> 5 votes
## Ruby, 142

```
' _     _  _     _  _  _  _  _
| |  | _| _||_||_ |_   ||_||_|
|_|  ||_  _|  | _||_|  ||_| _|'.lines{|l|puts x.chars.map{|i|l[i.to_i*3,3]}*''}

```

expects input in the variable `x`. examples:

```
x = '321'
#  _  _
#  _| _|  |
#  _||_   |

x = '42'
#      _
#  |_| _|
#    ||_

```

# Answer
> 5 votes
## python3.8.10 : ~~148~~ 138 bytes

Old (148):

```
a=input()
N=0x375fa9176b3538d93ca41ea
for i in 0,3,6:print(''.join(' |'[N&x<<i>0]+' _'[N&x<<i+1>0]+' |'[N&x<<i+2>0]for x in[1<<9*int(x)for x in a]))

```

New (138):

```
a=input()
N=0x375fa9176b3538d93ca41ea
for i in -1,2,5:print(''.join(' |_|'[(N&x<<i+k>0)*k]for x in[1<<9*int(x)for x in a]for k in(1,2,3)))

```

try the code here

# Answer
> 3 votes
## Golfscript - 97 chars

```
:*{32' _':$@'14'{?~!=}:&~32}%n*{:x' |':|\'1237'&$x'017'&|x'56'&}%n*{:x|\'134579'&$x'147'&|x'2'&}%

```

# Answer
> 3 votes
# D: 295 Characters

```
import std.stdio;void main(string[]a){string[3]o;foreach(c;a[1]){int n=cast(int)(c)-48;auto e=" ";o[0]~=n!=1&&n!=4?" _ ":"   ";o[1]~=!n||n>3&&n!=7?"|":e;o[1]~=n>1&&n!=7?"_":e;o[1]~=n<5||n>6?"|":e;o[2]~=!(n&1)&&n!=4?"|":e;o[2]~=!n||n>1&&n!=4&&n!=7?"_":e;o[2]~=n!=2?"|":e;}foreach(l;o)writeln(l);}

```

More Legibly:

```
import std.stdio;

void main(string[] a)
{
    string[3] o;

    foreach(c; a[1])
    {
        int n = cast(int)(c) - 48;
        auto e = " ";

        o[0] ~= n != 1 && n != 4 ? " _ " : "   ";

        o[1] ~= !n || n > 3 && n != 7 ? "|" : e;
        o[1] ~= n > 1 && n != 7 ? "_" : e;
        o[1] ~= n < 5 || n > 6 ? "|" : e;

        o[2] ~= !(n&1) && n != 4 ? "|" : e;
        o[2] ~= !n || n > 1 && n != 4 && n != 7 ? "_" : e;
        o[2] ~= n != 2 ? "|" : e;
    }

    foreach(l; o)
        writeln(l);
}

```

# Answer
> 3 votes
### Windows PowerShell, 127

```
$i="$input"[0..99]
'☺ ☺☺ ☺☺☺☺☺','♠☻♥♥♦♣♣☻♦♦','♦☻♣♥☻♥♦☻♦♥'|%{$c=$_
""+($i|%{('···0·_·0··|0·_|0|_|0|_·0|·|'-split0)[$c[$_-48]]})}

```

Since the strings contain some unpleasant-to-write characters, a hexdump for your convenience:

```
000: 24 69 3D 22 24 69 6E 70 │ 75 74 22 5B 30 2E 2E 39  $i="$input"[0..9
010: 39 5D 0A 27 01 00 01 01 │ 00 01 01 01 01 01 27 2C  9]◙'☺ ☺☺ ☺☺☺☺☺',
020: 27 06 02 03 03 04 05 05 │ 02 04 04 27 2C 27 04 02  '♠☻♥♥♦♣♣☻♦♦','♦☻
030: 05 03 02 03 04 02 04 03 │ 27 7C 25 7B 24 63 3D 24  ♣♥☻♥♦☻♦♥'|%{$c=$
040: 5F 0A 22 22 2B 28 24 69 │ 7C 25 7B 28 27 20 20 20  _◙""+($i|%{('
050: 30 20 5F 20 30 20 20 7C │ 30 20 5F 7C 30 7C 5F 7C  0 _ 0  |0 _|0|_|
060: 30 7C 5F 20 30 7C 20 7C │ 27 2D 73 70 6C 69 74 30  0|_ 0| |'-split0
070: 29 5B 24 63 5B 24 5F 2D │ 34 38 5D 5D 7D 29 7D     )[$c[$_-48]]})}

```

# Answer
> 3 votes
**Java Solution: ~~585~~ 570 Chars**

I don't think I'll be attempting any more golfing in Java...

```
import java.util.*;
public class CG997{public static void main(String[]args){
short[][]lets=new short[][]{{0,1,3,2,0,4,2,1,4},{0,0,3,0,0,4,0,0,4},{0,1,3,0,1,
4,2,1,3},{0,1,3,0,1,4,0,1,4},{0,0,3,2,1,4,0,0,4},{0,1,3,2,1,3,0,1,4},{0,1,3,2,1
,3,2,1,4},{0,1,3,0,0,4,0,0,4},{0,1,3,2,1,4,2,1,4},{0,1,3,2,1,4,0,0,4}};
String[]syms=new String[]{" ","_","|","  ","| "};
String s=new Scanner(System.in).nextLine();
for(int o=0;o<3;o++){for(char c:s.toCharArray()){for(int i =0;i<3;i++)
System.out.print(syms[lets[Short.parseShort(c+"")][i+o*3]]);
}System.out.println();}}}

```

# Answer
> 3 votes
# Bash, 11 characters

```
toilet "$i"

```

Yes I know, I'm cheating.

You need to have toilet installed.

# Answer
> 3 votes
# gForth, ~~186~~ 175 chars

New version:

```
: s query parse-word bounds s" D@DD@DDDDDb`ddfFF`fff`Fd`df`f`" bounds do cr 2dup do i c@ '0 - j + c@ 3 0 do dup 3 and s"  _|" drop + 1 type 4 / loop drop loop 10 +loop bye ; s

```

This actually bothers to exit (+3 chars) as well :). Here is the more readable version, it does some bit-packing to reduce the LUT size by 1/3, but the resulting code is more complex so it's not much of a savings:

```
: 7s query parse-word bounds
    s" D@DD@DDDDDb`ddfFF`fff`Fd`df`f`"
    bounds do
        cr
        2dup do
            i c@ '0 - j + c@
            3 0 do
                dup 3 and
                s"  _|" drop + 1 type
                4 / \ shorter than an rshift
            loop
            drop
        loop
    10 +loop bye ;
7s

```

Old version:

```
: s query parse-word bounds s"  _     _  _     _  _  _  _  _ | |  | _| _||_||_ |_   ||_||_||_|  ||_  _|  | _||_|  ||_|  |" bounds do cr 2dup do i c@ '0 - 3 * j + 3 type loop 30 +loop ; s

```

This leaves the stack unbalanced and doesn't bother to exit the interpreter. Here is a cleaner more readable version

```
: 7s query parse-word bounds
    s"  _     _  _     _  _  _  _  _ | |  | _| _||_||_ |_   ||_||_||_|  ||_  _|  | _||_|  ||_|  |"
    bounds do
        cr
        2dup do
            i c@ '0 - 3 * j + 3 type
        loop
    30 +loop 2drop bye ;
7s

```

# Answer
> 3 votes
# Java 8, ~~280~~ 274 bytes

```
interface M{static void main(String[]a){String x="",y=x,z=x;for(int c:a[0].getBytes()){c-=48;x+=" "+(c==4|c==1?" ":"_")+" ";y+=(c==7|c>0&c<4?" ":"|")+(c==7|c<2?" ":"_")+(c>4&c<7?" ":"|");z+=(c%2<1&c!=4?"|":" ")+(c%3==1?" ":"_")+(c==2?" ":"|");}System.out.print(x+"\n"+y+"\n"+z);}}

```

-6 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
interface M{                     // Class
  static void main(String[]a){   //  Mandatory main-method
    String x="",                 //   String for row 1, starting empty
           y=x,                  //   String for row 2, starting empty
           z=x;                  //   String for row 3, starting empty
    for(int c:a[0].getBytes()){  //   Loop over the bytes of the input
      c-=48;                     //    Convert the byte to integer
      x+=                        //    Append to row 1:
         c==4|c==1?              //     If the digit is a 1 or 4:
            "   "                //       Append three spaces
           :                     //      Else:
            " _ ";               //       Append a space + underscore + space instead
      y+=                        //    Append to row 2:
         (c==7|c>0&c<4?          //      If the digit is 1, 2, 3, or 7:
           " "                   //       Append a space
          :                      //      Else:
           "|")                  //       Append a pipe
         +(c==7|c<2?             //     +If the digit is 0, 1, or 7:
            " "                  //       Append a space
           :                     //      Else:
            "_")                 //       Append an underscore
         +(c>4&c<7?              //     +If the digit is 5 or 6:
            " "                  //       Append a space
           :                     //      Else:
            "|");                //       Append a pipe
      z+=                        //    Append to row 3:
         (c%2<1&c!=4?            //      If the digit is 0, 2, 6 or 8:
           "|"                   //       Append a pipe
          :                      //      Else:
           " ")                  //       Append a space
          +(c%3==1?              //     +If the digit is 1, 4, or 7:
             " "                 //       Append a space
            :                    //      Else:
             "_")                //       Append a pipe
          +(c==2?                //     +If the digit is 2:
             " "                 //       Append a space
            :                    //      Else:
             "|");               //       Append a pipe
    }                            //   End of loop
    System.out.print(x+"\n"+y+"\n"+z);
                                 //   Print the three rows
  }                              //  End of main-method
}                                // End of class

```

As function this would be **212 bytes** instead.

# Answer
> 3 votes
# JavaScript (V8), ~~118~~ 115 bytes

-3 bytes: realised a cheaper way to loop through `|_|`

```
n=>[613550340,2132540234,1866373582].map(d=>n.replace(/./g,c=>(i=1<<c*3,g=s=>d&(i*=2)?s:' ')`|`+g`_`+g`|`)).join`
`

```

Try it online!

Takes input as a string of digits, uses three magic numbers which represent the state of each segment for each digit; every three bits is a digit.

Ungolfed and explained

```
n => [ // magic numbers
              //      9   8   7   6   5   4   3   2   1   0
  613550340,  // = 0b010_010_010_010_010_000_010_010_000_010_0
  2132540234, // = 0b111_111_100_011_011_111_110_110_100_101_0
  1866373582  // = 0b110_111_100_111_110_100_110_011_100_111_0
].map(d => n.replace(/./g,
  c => (
    i = 1 << c * 3, // initialise i to first bit of digit
    g = s => d & (i *= 2) ? s : ' ' // function to check bits
  )`|` + g`_` + g`|` // do function on each of '|_|'
)).join`

```

# Answer
> 2 votes
## Java, 2,095

```
public class DigitalNumber {
    public static void main(String args[]){
        char[][] panel = new char[3][120]; //A 20 digit panel!
        int digXIndex = 0;int digYIndex = 0;
        for (int i=0;i<args[0].length(); i++){
            int dig=Integer.parseInt(""+args[0].charAt(i));
            panel[digXIndex][digYIndex]=32;
            digYIndex++;
            if (dig!=1 && dig!=4)
                panel[digXIndex][digYIndex]='_';
            else
                panel[digXIndex][digYIndex]=32;
            digYIndex++;
                panel[digXIndex][digYIndex]=32;
            digYIndex=3*i;
            digXIndex++;
            if (dig!=1 && dig!=2 && dig!=3 && dig!=7)
                panel[digXIndex][digYIndex]='|';
            else
                panel[digXIndex][digYIndex]=32;
            digYIndex++;
            if (dig!=1 && dig!=0 && dig!=7)
                panel[digXIndex][digYIndex]='_';
            else
                panel[digXIndex][digYIndex]=32;
            digYIndex++;
            if (dig!=6 && dig!=5)
                panel[digXIndex][digYIndex]='|';
            else
                panel[digXIndex][digYIndex]=32;
            digYIndex=3*i;
            digXIndex++;
            if (dig!=6 && dig!=8 && dig!=2 && dig!=0)
                panel[digXIndex][digYIndex]=32;
            else
                panel[digXIndex][digYIndex]='|';
            digYIndex++;
            if (dig!=7 && dig!=4 && dig!=1)
                panel[digXIndex][digYIndex]='_';
            else
                panel[digXIndex][digYIndex]=32;
            digYIndex++;
            if (dig!=2)
                panel[digXIndex][digYIndex]='|';
            else
                panel[digXIndex][digYIndex]=32;
            digXIndex=0;
            digYIndex+=(i*3)+1;
        }
        for (int i=0; i<3; i++){
            for (int j=0; j<120; j++)
                if (panel[i][j]!=0)
                System.out.print((char)(panel[i][j]));
                else
                    System.out.print("");
            System.out.println();
        }
    }
}

```

SAMPLE I/O

```
java DigitalNumber 98765432109876543210
     _  _  _  _  _     _  _     _  _  _  _  _  _     _  _     _
    |_||_|  ||_ |_ |_| _| _|  || ||_||_|  ||_ |_ |_| _| _|  || |
     _||_|  ||_| _|  | _||_   ||_| _||_|  ||_| _|  | _||_   ||_|

```

# Answer
> 2 votes
## C# 369 Characters

```
static void Main(string[] a){var b = new[] {123,72,61,109,78,103,119,73,127,111};var g = new[]{" _  ","|","_","| ","|","_","| "};a[0].ToCharArray().SelectMany((x,w)=>g.Select((y,i)=>new{s=((b[x-48]>>i&1)==1)?y:new String(' ',y.Length),j=i,v=w})).GroupBy(z=>(z.j+2)/3).ToList().ForEach(q=>Console.WriteLine(String.Join("", q.OrderBy(l=>l.v).Select(k=>k.s).ToArray())));}

```

I could easily cut *a few* characters out. The point was more to abuse LINQ :)

More whitespace version:

```
static void Main(string[] a)
{
    var b = new[] {123, 72, 61, 109, 78, 103, 119, 73, 127, 111};
    var g = new[] { " _  ", "|", "_", "| ", "|", "_", "| " };
    a[0].ToCharArray().SelectMany(
        (x,w)=>g.Select(
           (y,i)=>new{s=((b[x-48]>>i&1)==1)?y:new String(' ',y.Length),j=i,v=w}))
            .GroupBy(z=>(z.j+2)/3).ToList().ForEach(
            q=>Console.WriteLine(
                String.Join("", q.OrderBy(l=>l.v).Select(k=>k.s).ToArray())));
}

```

# Answer
> 2 votes
# Python, ~~218~~ ~~180~~ 176

`b=map(int,raw_input());a=map(int,bin(914290166014670372457936330)[2:]);c=' |_';p=lambda k:''.join(c[a[9*n+k]]+c[2*a[9*n+1+k]]+c[a[9*n+2+k]]for n in b)+'\n';print p(6)+p(0)+p(3)`

With line breaks:

```
b=map(int,raw_input())
a=map(int,bin(914290166014670372457936330)[2:])
p=lambda k:''.join(' |'[a[9*n+k]]+' _'[a[9*n+1+k]]+' |'[a[9*n+2+k]]for n in b)+'\n'
print p(6)+p(0)+p(3)

```

# Answer
> 2 votes
# PHP, ~~140~~ ~~136~~ ~~133~~ ~~131~~ ~~129~~ 128 bytes

I could save ~~5~~ 7 more with extended ascii: one each for `"| _"` and the linebreak, three for `~"z/]{4lno~|"` (bitwise negation would turn everything to extended ascii characters = no special characters, and PHP doesn´t need quotes there), two for `-1` (it´s only there to keep the map in standard ascii). But for readability and compatibility, I stay with standard ascii.

```
for(;""<$c=$argv[1][$i++];)for($n=753754680;$n>>=3;)$r[$p++%3].="| _"[ord(~"z/]{4lno~|"[$c])-1>>$n%8&1?:$n&2];echo join("
",$r);

```

**the bitmap**

* Take LEDS `_`,`|_|`, `|_|` as bits `-6-`,`024`,`135` (bit number &2 is 0 for vertical LEDs)
* Create bitmaps for numbers 0..9: `[123,48,94,124,53,109,111,112,127,125]`
* Decrease by 1 to make them all printable ascii codes -\> `"z/]{4lno~|"`
* negate -\> `~"z/]{4lno~|"` (allows ternary shorthand in character selection)

**the template**

* use `7` for the spaces -\> `767`,`024`,`135`
* regroup by columns instead of rows -\> `701`,`623`,`745` (renders `$p=0` obsolete)
* reverse -\> `547326107` (read the map from right to left; allows arithmetic looping)
* append zero -\> `5473261070` (allows to combine shift with test in loop head)
* read octal, convert to decimal -\> `753754680` (two bytes shorter: one digit and the prefix)

**breakdown**

```
for(;""<$c=$argv[1][$i++];) // loop through input characters
    for($n=753754680;$n>>=3;)   // loop through template
        $r[$p++%3].="| _"[          // append character to row $p%3:
            ord(~"z/]{4lno~|"[$c])-1// decode bitmap
                >>$n%8&1            // test bit $n%8 (always 1 for bit 7)
            ?                       // if set: 1 (space)
            :$n&2                   // else: 2 (underscore) for bits 2,3,6; 0 (pipe) else
        ];
echo join("\n",$r);         // print result

```

# Answer
> 2 votes
# Powershell, 114 bytes

```
param($a)6,3,0|%{$l=$_
-join($a|% t*y|%{('   0 _ 0 _|0|_ 0| |0  |0|_|'-split0)[(+('f-SR5Z^mvr'["$_"])-shr$l)%8]})}

```

Test script:

```
$f = {

param($a)6,3,0|%{$l=$_
-join($a|% t*y|%{('   0 _ 0 _|0|_ 0| |0  |0|_|'-split0)[(+('f-SR5Z^mvr'["$_"])-shr$l)%8]})}

}

&$f "1234567890"
&$f "81"

```

Output:

```
    _  _     _  _  _  _  _  _
  | _| _||_||_ |_   ||_||_|| |
  ||_  _|  | _||_|  ||_| _||_|
 _
|_|  |
|_|  |

```

Main idea:

Each standard digital clock style number contains 3 lines. Moreover, the first line contains only 2 options. A total of 6 options. Therefore, 7 bits are enough to encode each digit.

```
line str=@('   ', ' _ ', ' _|', '|_ ', '| |', '  |', '|_|')

#    line str    binary       dec    ASCII
-    --------    ---------    ---    -----
0 -> 1
     4
     6        -> 1 100 110 -> 102 -> 'f'

1 -> 0
     5
     5        -> 0 101 101 ->  45 -> '-'

...

8 -> 1
     6
     6        -> 1 110 110 -> 118 -> 'v'

9 -> 1
     6
     2        -> 1 110 010 -> 114 -> 'r'

```

So, the string `f-SR5Z^mvr` encodes all segments for all standard digital clock style numbers.

Note: The order of the `line str` was specially selected so that all codes were in the interval `32..126`.

# Answer
> 2 votes
# Vyxal `jṠ`, 40 bytes

```
»*ż↵↲ṡŀ≬₍ṡfl₆ǎ8≠∇ƈH»`_ |`τ3/₀/ƛ£⁰ƛ¥nIi;ṅ

```

Try it Online!

A mess. Uses base-3 compression.

```
»...»                     # Compressed integer containing all digits
     `_ |`τ               # Decompress by custom base-3
           3/             # Divide into 3
             ₀/           # Divide each piece into 10
               ƛ          # Map this new list to...
                £         # Store to register
                 ⁰ƛ    ;  # Map this new input to...
                   ¥      # Push register
                    nIi   # Get correct value
                        ṅ # Join
                          # (Implicit) Join by newlines

```

# Answer
> 1 votes
# Ocaml, 268

```
let t=function|'1'|'4'->"   "|_->" _ "let m=function|'0'->"| |"|'1'|'7'->"  |"|'2'|'3'->" _|"|_->"|_|"|'5'|'6'->"|_ "let b=function|'0'|'8'->"|_|"|'1'|'4'|'7'->"  |"|'2'->"|_ "|_->" _|"let f s=let g h=String.iter(fun c->print_string(h c))s;print_newline()ing t;g m;g b

```

Readable version

```
let t = function
  | '1'
  | '4' -> "   "
  | _ -> " _ "
let m = function
  | '0' -> "| |"
  | '1'
  | '7' -> "  |"
  | '2'
  | '3' -> " _|"
  | _ -> "|_|"
  | '5'
  | '6' -> "|_ "
let b = function
  | '0'
  | '8' -> "|_|"
  | '1'
  | '4'
  | '7' -> "  |"
  | '2' -> "|_ "
  | _ -> " _|"
let f s =
  let g h =
    String.iter (fun c -> print_string (h c)) s;
    print_newline () in
  g t;
  g m;
  g b

```

# Answer
> 1 votes
## Ghostscript ~~(270)~~ ~~(248)~~ (214)

*Edit:* More substitutions. Removed space between digits.

*Edit:* Even more substitutions. Main loop now looks like what it does!

```
/F{forall}def[48<~HUp;::1ncBInp~>{1 index 1 add}F
pop/*{dup
2 idiv exch
2 mod
1 eq}/P{print}/#{( )P}/?{ifelse
P}/O{{( )}?}/|{*{(|)}O}/_{*{(_)}O}>>begin[[[[ARGUMENTS{{load
# _ #}F()=]2{{| _ |}F()=]}repeat]pop[[[[}F

```

Uses ghostscript's argument-processing feature: invoke with `gs -dNODISPLAY -- digit.ps 012 345 6789`.

# Answer
> 1 votes
### Delphi || 453 (568 With format)

Not even close enough to win but it was fun to do ^.^

```
const asc: array[0..9] of array[0..2] of string = ((' _ ','| |','|_|'),('   ','  |','  |'),(' _ ',' _|','|_ '),(' _ ',' _|',' _|'),('   ','|_|','  |'),(' _ ','|_ ',' _|'),(' _ ','|_ ','|_|'),(' _ ','  |','  |'),(' _ ','|_|','|_|'),(' _ ','|_|',' _|'));var s,l:string;x,i:integer;begin Readln(s);s:=StringReplace(s,' ','',[rfReplaceAll]);for I := 0 to 2 do begin l:='';for x := 1 to length(s) do l := l + asc[StrToInt(s[x])][i];writeln(l);end;readln;end.

```

### With format

```
const
asc: array[0..9] of array[0..2] of string = (
  (' _ ','| |','|_|'),
  ('   ','  |','  |'),
  (' _ ',' _|','|_ '),
  (' _ ',' _|',' _|'),
  ('   ','|_|','  |'),
  (' _ ','|_ ',' _|'),
  (' _ ','|_ ','|_|'),
  (' _ ','  |','  |'),
  (' _ ','|_|','|_|'),
  (' _ ','|_|',' _|'));
var
s,l:string;
x,i:integer;
begin
    Readln(s);
    s:=StringReplace(s,' ','',[rfReplaceAll]);
    for I := 0 to 2 do
    begin
      l:='';
      for x := 1 to length(s) do
        l := l + asc[StrToInt(s[x])][i];
      writeln(l);
    end;
    readln

```

end.

# Answer
> 1 votes
# Perl 5 `-F`, 96 bytes

```
map{@m=/./g;say map{substr'    _  _||_ | |  ||_|',3*$m[$_],3}@F}1011011111,4522633566,6532526562

```

Try it online!

The string  `_ _||_ | | ||_|` represents the possible "cross sections" of the digits (grabbed the idea from @mazzy's PowerShell solution). The numbers in the list `1011011111,4522633566,6532526562` represent indices into that string for the first, second, and third line of each of the digits 0-9. The index must be multiplied by 3 to get to the correct position. This loops over each character input (stored in the `@F` array by the `-F` option on the command line), finds the correct index into the string for that input, and then outputs the result.

### Old version: Perl 5 `-n`, 102 bytes

```
for$b(' a ',dbe,fcg){say s%.%'$b=~y/'.(b,abcdf,dg,df,acf,ef,e,bcdf,Z,f)[$&]."/ /r=~y/a-z/___|/r"%geer}

```

Try it online!

Considers the characters of the display to be named like this: $$\begin{array}{|c|c|c|} \hline & a & \\ \hline d &b & e \\ \hline f & c & g \\ \hline \end{array}$$

The code iterates over strings representing each line of that table `(' a ',dbe,fcg)`. On each of those, it changes the elements turned off into spaces. This information is in the list `(b,abcdf,dg,df,acf,ef,e,bcdf,z,f)`. It uses the current element of the input (stored in `$_` by the commandline switch and extracted by the pattern match into `$&`) to index into that list. Finally, the letters a, b, and c are changed to underscores (`_`) and all other letters into pipes (`|`).

# Answer
> 1 votes
# 05AB1E, 36 bytes

```
•ʒïgÈ¨&Û≠∍›vâsŸ”_‡y•…| _ÅвJ3ôTäÅвø»

```

Outputs with additional single space between the output-digits. If this is not allowed, it'll be 1 byte longer by adding a `J` before the `»`.

Try it online.

**Explanation:**

```
•ʒïgÈ¨&Û≠∍›vâsŸ”_‡y•
          # Push compressed integer 5210925748351095970666976465591163407510385
 …| _     # Push string "| _"
     Åв   # Convert the integer to this custom base (basically convert it to
          # base-length - 3 in this case - and index each into the string)
       J  # Join this list of characters to a single string:
          #  " _ | ||_|     |  | _  _||_  _  _| _|   |_|  | _ |_  _| _ |_ |_| _   |  | _ |_||_| _ |_| _|"
3ô        # Split it into triplets
  Tä      # Split that into 10 equal-sized parts
    Åв    # Convert the (implicit) input-integer to this custom base
      ø   # Zip/transpose; swapping rows/columns
       »  # Join each inner list by spaces, and then each string by newlines
          # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•ʒïgÈ¨&Û≠∍›vâsŸ”_‡y•` is `5210925748351095970666976465591163407510385`.
See this 05AB1E tip to understand how the ASCII-art string `" _ | ||_| | | _ _||_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_||_| _ |_| _|"` is compressed.

# Answer
> 1 votes
# Factor \+ `lcd`, 3 bytes

```
lcd

```

Try it online!

# Answer
> 1 votes
# Vyxal, 33 bytes

```
»@Ǐ+Ẇ₃e⋏UWṡ:≠7ẏŀz→=»`| _`τ₀/3/τ∩⁋

```

Ports the 05AB1E answer.

Try it Online!

## How?

```
»@Ǐ+Ẇ₃e⋏UWṡ:≠7ẏŀz→=»`| _`τ₀/3/τ∩⁋
»@Ǐ+Ẇ₃e⋏UWṡ:≠7ẏŀz→=»              # Push compressed integer 5210925748351095970666976465591163407510385
                    `| _`         # Push string "| _"
                         τ        # Convert the integer to this custom base
                          ₀/      # Split into ten pieces
                            3/    # Split each into three pieces
                              τ   # For each string, convert the (implicit) input to this custom base
                               ∩  # Transpose
                                ⁋ # Join on newlines

```

# Answer
> 0 votes
## Perl (~~182~~ 180)

```
#!perl -l
$_=<<7;
 _     _  _     _  _  _  _  _
| |  | _| _||_||_ |_   ||_||_|
|_|  ||_  _|  | _||_|  ||_| _|
7
@b=map{[/(...)/g]}split/\n/;@d=split//,<>;for$p(@b){print map$p->[$_],@d}

```

reads from STDIN.

```
$ perl 7segment.pl
1234567890987654321
    _  _     _  _  _  _  _  _  _  _  _  _  _     _  _     _
  | _| _||_||_ |_   ||_||_|| ||_||_|  ||_ |_ |_| _| _|  || |
  ||_  _|  | _||_|  ||_| _||_| _||_|  ||_| _|  | _||_   ||_|

```

# Answer
> 0 votes
# **Python, 227 chars**

```
a="   ";b=" _ ";c="|_|";d="| |";e="|  ";f="  |";g="|_ ";h=" _|"
z=[[b,d,c],[a,f,f],[b,h,g],[b,h,h],[a,c,f],[b,g,h],[b,g,c],[b,f,f],[b,c,c],[b,c,h]]
x=map(int,raw_input())
for i in range(3):
 for j in x:
  print z[j][i],
 print

```

Simple and straightforward.

# Answer
> 0 votes
# Python 3.4.3 - ~~1514~~ 858 bytes

The temptation to solve this was too great not to sign up and answer =P

I'm a bit new to Python, so I formatted my program nice and neat (or at least I did). Improvements are greatly appreciated!

```
import sys;l1,l2,l3,l4,l5="";num=input()
for c in num:
    if c=="1":
        l1+=" oo  ";l2+="  o  ";l3+="  o  ";l4+="  o  ";l5+="oooo "
    if c=="2":
        l1+="oooo ";l2+="   o ";l3+="oooo ";l4+="o    ";l5+="oooo "
    if c=="3":
        l1+="oooo ";l2+="   o ";l3+=" ooo ";l4+="   o ";l5+="oooo "
    if c=="4":
        l1+="o  o ";l2+="o  o ";l3+="oooo ";l4+="   o ";l5+="   o "
    if c=="5":
        l1+="oooo ";l2+="o    ";l3+="oooo ";l4+="   o ";l5+="oooo "
    if c=="6":
        l1+="oooo ";l2+="o    ";l3+="oooo ";l4+="o  o ";l5+="oooo "
    if c=="7":
        l1+="oooo ";l2+="   o ";l3+="   o ";l4+="   o ";l5+="   o "
    if c=="8":
        l1+="oooo ";l2+="o  o ";l3+="oooo ";l4+="o  o ";l5+="oooo "
    if c=="9":
        l1+="oooo ";l2+="o  o ";l3+="oooo ";l4+="   o ";l5+="oooo "
    if c=="0":
        l1+="oooo ";l2+="o  o ";l3+="o  o ";l4+="o  o ";l5+="oooo "
print(l1+"\n"+l2+"\n"+l3+"\n"+l4+"\n"+l5)

```

Edit: Shortened variable names, used ; to shorten, only one space at end of output numbers, defined variables all at once.

New lines are 2 bytes (CRLF) and I used tabs instead of 4 spaces.

# Answer
> 0 votes
# SmileBASIC, 216 bytes

```
?INPUT N$DIM A[14]COPY A,@A@A
DATA 1,0,0,1,3,1,1,3,0,4,3,4,1,6FOR D=0 TO LEN(N$)-1X=ASC("w$]m.k{%\o"[VAL(N$[D])])FOR I=0TO 6T=I*2IF X<<31THEN GBOX A[T]+D*5,A[T+1],A[T]+D*5+!(I MOD 3),A[T+1]+!!(I MOD 3)
X=X/2NEXT
NEXT

```

Using graphics instead of text, because it's probably shorter.

Explanation:

```
PRINT 'so the input and output don't overlap
INPUT NUMBER$ 'get number
DIM PTS[7*2] 'locations of segments
COPY PTS,@PTDATA 'copy data into array
@PTDATA
DATA 1,0,0,1,3,1,1,3,0,4,3,4,1,6 'stored as x,y,x,y,...
FOR DIGIT=0 TO LEN(NUMBER$)-1
 NUM=ASC("w$]m.k{%\o"[VAL(NUMBER$[DIGIT])]) 'get digit data. That data string doesn't have any non-ASCII characters, except \ which is 127 in SB.
 FOR I=0 TO 7-1 'draw each segment
  T=I*2 'position of point in array
  IF X AND 1 THEN GLINE PTS[T]+DIGIT*5,PTS[T+1],PTS[T]+DIGIT*5+!(I MOD 3),PTS[T+1]+!!(I MOD 3) 'draw segment. I MOD 3 determines whether it's horizontal or vertical.
  X=X>>1 'shift to next bit
 NEXT
NEXT

```

# Answer
> 0 votes
# C++, ~~230~~ ~~229~~ ~~225~~ ~~223~~ ~~218~~ ~~207~~ ~~204~~ 198 bytes

```
#import<iostream>
#define d for(auto
std::string v[3],t,g="|_| =2$0^262\'032;2$2?272";main(){std::cin>>t;d i:t)d j:{0,1,2})d k:{0,1,2})v[k]+=g[g[i*2-92+!k]>>j+k/2*3&1?j:3];d j:v)std::cout<<j<<'\n';}

```

Reads from stdin and output to stdout.

**Explanation:**

```
#import<iostream>                // string inside

std::string v[3], t, g="|_| "    // symbol on different horizontal position
      "=2$0^262\'032;2$2?272";   // space(0) or not(1) for each number and position
                                 // binary representation, last 6 bits is used
                                 // even positions are for row 1, 2; odds are for row 0

main() {
    std::cin>>t;                 // input
    for (auto i:t)               // for each character
        for (auto j:{0,1,2})     // for each horizontal position
            for (auto k:{0,1,2}) // for each vertical position
                v[k]+=g[         // use first four chars only
                    g[i*2-92     // i*2-96 is number*2, +4 to skip first four
                        +!k]     // row 0 uses another character
                    >>j+k/2*3    // (k==2?3:0)+j, the expected bit
                    &1           // extract the bit
                    ?j:3         // space or not space
                ];

    for (auto j:v) std::cout<<j<<'\n'; // output
}

```

# Answer
> 0 votes
## JavaScript ~~137~~ 133

```
r=(x,i=0,o='')=>{for(m of x){c="ŞHŦŬxļ>ňžŸ".charCodeAt(m)>>1<<i
for(j=3;j--;)o+=c&256>>j?'|_'[j%2]:' '}
return i<7?r(x,i+3,o+"\n"):o}

```

# Answer
> 0 votes
# JavaScript (Node.js), 188 bytes

```
s=>[0,1,2].map(i=>s.replace(/./g,e=>[(t=(h,j='|',k=' ')=>(''+h).includes(e)?j:k)(2370+(b='5689'),' _ ','   '),t(104+b)+t(234+b,'_')+t(2347890),t(12680)+t(230+b,'_')+t(3704+b)][i])).join`
`

```

Try it online!

Not the shortest but uses a different approach.

# Answer
> 0 votes
# C (gcc), 329 bytes

```
#define A 95:32
#define B '|':32
#define C s[0][k])?
#define I index(
#define P printf(
a;n;k;
main(c,s)char**s;{s++;a=strlen(*s);for(k=0;k<=a;k==a?k=0,n>4?k=2*a:n++:k++){!n&&P" %c  ",!I"14",C A);n==2&&P"%c%c%c ",!I"1237",C B,!I"170",C A,!I"56",C B);n==4&&P"%c%c%c ",!I"134579",C B,!I"147",C A,!I"2",C B);n&1?P"\n"),n++,k=-1:0;}}

```

Try it online!

# Answer
> 0 votes
# Batch, ~~307~~ 301 bytes

```
@echo off&!! 2>nul||cmd/q/v/c%0&&exit/b&set/px=&set n= _     _  _     _  _  _  _  _ 1 1  1 _1 _11_11_ 1_   11_11_11_1  11_  _1  1 _11_1  11_1 _1
for %%i in (0,3,6)do set t=&set j=0&call:l %%i&echo ␛[m!t:1=^|!
exit/b
:l
set/ad=3*!x:~%j%,1!+%~10,j+=1
set t=%t%!n:~%d%,3!&if .!x:~%j%! neq . goto:l
exit/b

```

represents the nonprintable "" character and is used to make sure the first line is blank when the input only has `1`s and `4`s.

# Answer
> -1 votes
Perl, 145 characters

```
$i=<>;for$s(6,3,0){for($i=~/./g){$v=(175,9,158,155,57,179,183,137,191,187)[$_]>>$s;$o.=($v&4?'|':$").($v&2?'_':$").($v&1?'|':$")}$o.="
"}print$o

```

Ungolfed:

```
# Read STDIN
$i = <>;
# Amount to bit shift later
for $s (6,3,0)
{
  # For each character C from STDIN
  for ($i =~ /./g)
  {
    # Get the Cth array index, bit shifted right by $s
    $v = (175, 9, 158, 155, 57, 179, 183, 137, 191, 187)[$_]>>$s;
    # Concatenate each character if the bitwise masked value says it should be there
    $o .= ($v & 4 ? '|' : $") .
          ($v & 2 ? '_' : $") .
          ($v & 1 ? '|' : $");
  }
  # Concatenate a newline
  $o .= "
";
}
# Print the result
print $o;

```

---
Tags: code-golf, ascii-art
---


# Question
Title: Convert the type modifiers from prefix to C-fix
Given a base type `T`, this can be augmented with `*` or `[]`, each meaning pointer and array. For example, `[]*T` means "array of pointer to `T`" and `*[]T` means "pointer to array of `T`".

Let's call `*` and `[]` type *modifiers*. C has a way of ordering these modifiers tied to the evaluation order. `[]*T` in C-style becomes `T *[]`, and `*[]T` becomes `T (*)[]`. You may be able to understand how the conversion works by having a look at the examples below. An explanation is also given at the end of this post.

```
* -> *
[] -> []
[]* -> *[]
*[] -> (*)[]
*[]* -> *(*)[]
[]*[] -> (*[])[]
*[][]* -> *(*)[][]
[]**[] -> (**[])[]
[]*[]* -> *(*[])[]
*[]*[] -> (*(*)[])[]

```

Your program or function should process an input string to an output string as the examples above. The input will only contain `*` and `[]` without whitespaces.

---

This challenge is this challenge in reverse, simplified.

---

Rules for C-fix:

* All of the `*`s always come before all of the `[]`s (in real C code, the variable name comes between the last `*` and the first `[]`).
* Evaluation starts in the middle, where the variable name would be.
* If there is both a `*` on the left and a `[]` on the right, without any parentheses to determine the order, the `[]` is bound first, and comes first in prefix:
    + C-fix `*[]`
    = C `*a[]` (where `a` is the variable name) = "array of pointers" =
    prefix `[]*`.
* In order to change the order of evaluation so that a `*` gets bound first, it must be put in parentheses (with where the variable name would be):
    + prefix `*[]`
    = "pointer to an array" = C `(*a)[]`(where `a` is the variable name) =
    C-fix `(*)[]`.

---

From the last example, `(*(*)[])[]` in actual C code would be something like `int (*(*a)[])[]` (where `a` is the variable name). The evaluation starts from `a` and `[]` is bound first unless a set of parentheses blocks the binding.

If you put `int (*(*a)[])[]` to cdecl.org, the output is "declare a as pointer to array of pointer to array of int". This is because:

* The first `*` is bound first due to the parentheses.
* There are no parentheses between the variable name and the `[]`, causing that to be bound before the next `*`.
* Then, the next `*` is bound because it is in the parentheses with the variable name, whereas the remaining `[]` is not.
* Finally, the remaining `[]` is bound.

This is `*[]*[]int a` in prefix. Hence, `*[]*[] -> (*(*)[])[]`.

# Answer
> 4 votes
# Curry (PAKCS), 90 bytes

```
f s@(""?"[]")=s
f(s++"*")='*':f s
f(s++"*[]")="(*"++f s++")[]"
f(s++"][]")=f(s++"]")++"[]"

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 52 bytes

```
^((.])*)(\**)
$3$1¶
{G`.
(.+)¶((.])+)(\**)
$4($1)$2¶

```

Try it online! Link includes test cases. Explanation:

```
^((.])*)(\**)
$3$1¶

```

Process any initial `[]`s or `*`s into an output line.

```
{`

```

Repeat until there is nothing left to process.

```
G`.

```

Delete the original input line once there is nothing left.

```
(.+)¶((.])+)(\**)
$4($1)$2¶

```

Process some more `[]`s and `*`s.

# Answer
> 1 votes
# Charcoal, 27 bytes

```
ＦＳ≔⎇⁼ι*⁺ιω⁺⎇∧ω⁼§ω⁰*⪫()ωωιωω

```

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

```
ＦＳ

```

Loop over all of the input characters.

```
≔⎇⁼ι*⁺ιω⁺⎇∧ω⁼§ω⁰*⪫()ωωιω

```

If the current character is a `*`, then prepend it. Otherwise, append it, but if the output string starts with a `*` then wrap it in `()` first.

```
ω

```

Output the final string.

# Answer
> 1 votes
# Python 3.8+, <sup>~~92~~</sup> 83 bytes

```
f=lambda p,c="":f(p[1:],["*"+c,[f"({c})",c][c[:1]!="*"]+p[0]][p[0]>"*"])if p else c

```

Try it online!

# Answer
> 1 votes
# C (clang), ~~119~~ 117 bytes

*-2 bytes thanks to @ceilingcat*

```
*b;f(char*a,l){return l&&asprintf(&b,a[--l]<43?"*%*s":a[l]<93?:--l&&a[l-1]<43?l--,"(*%*s)[]":"%*s[]",l,f(a,l))?b:"";}

```

Try it online! Takes input as a character array and its length; returns an allocated string.

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


title: Spaceship shooter

text:
# Question
Title: Spaceship shooter
Your task is to output a spaceship of size `n` with shooters/guns and `n` bullets of character `-` (with spaces in between each bullet) for each gun

# Rules

* If `n` is odd, you must output the guns every even numbered row
* If `n` is even, you must output the guns every odd numbered row
* All rows with guns must have `n+1` `#` characters
* The spaceship is 3 characters tall for all inputs
* `n` must be greater than 0

# Testcases

```
1
->
#
## -
#

2
->
### - -
##
### - -

3
->
###
#### - - -
###

```

Trailing spaces are allowed

This is , so shortest code wins!

# Answer
# 05AB1E, 18 bytes

```
'#×DĆ„ -I×«IFs}DŠ»

```

Try it online or verify some more test cases.

**Explanation:**

```
'#×        '# Repeat "#" the (implicit) input amount of times as string
   D        # Duplicate this string
    Ć       # Enclose; append its own character to increase its size by 1
     „ -I×  # Repeat " -" the input amount of times as string
          « # Append it to the earlier string
IF }        # Loop the input amount of times:
  s         #  Swap the two values on the stack each iteration
            # (basically swap for odd values; and not for even)
    D       # Duplicate the top string
     Š      # Triple-swap the three values on the stack from a,b,c to c,a,b
      »     # Join the three strings on the stack by newlines
            # (after which it is output implicitly as result)

```
> 1 votes

# Answer
# , 40 38 36 35 bytes

```
' -#'{~3{.2&||.4$$&2,:2,$&2,0 1$~+:

```

Try it online!

Consider input 2:

* `0 1$~+:` Extends `0 1` to twice the input size:

```
0 1 0 1

```
* `$&2,` Extend `2` to the input size, and prepend it:

```
2 2 0 1 0 1

```
* `2,` Prepend one more two:

```
2 2 2 0 1 0 1

```
* `$&2,:` Extend `2` to the input size, and prepend it as a new table item, with zero fill:

```
2 2 0 0 0 0 0
2 2 2 0 1 0 1

```
* `4$` Extend this new list to 4 elements:

```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
2 2 0 0 0 0 0
2 2 2 0 1 0 1

```
* `2&||.` Rotate it left 0 times for even numbers, 1 time for odd:

```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
2 2 0 0 0 0 0
2 2 2 0 1 0 1

```
* `3{.` Take first 3:

```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
2 2 0 0 0 0 0

```
* `' -#'{~` Convert to ascii:

```
##
### - -
##

```
> 4 votes

# Answer
# JavaScript (Node.js), 75 bytes

```
n=>(r=x=>x-3?"#".repeat(n)+(x%2-n%2?"":"#"+" -".repeat(n))+`
`+r(++x):"")``

```

Try it online!
> 2 votes

# Answer
# Charcoal, 21 bytes

```
ＮθＥ³⁺×θ#⎇﹪⁺θι²ω⁺#× -θ

```

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

```
Ｎθ                      First input as an integer
  Ｅ³                    Map over 3 rows
       #                Literal string `#`
     ×                  Repeated by
      θ                 Input integer
    ⁺                   Concatenated with
           θ            Input integer
          ⁺             Plus
            ι           Current index
         ﹪              Modulo
             ²          Literal integer `2`
        ⎇               If nonzero then
              ω         Empty string else
                #       Literal string `#`
               ⁺        Concatenated with
                   -    Literal string ` -`
                 ×      Repeated by
                    θ   Input integer
                        Implicitly print

```
> 2 votes

# Answer
# Python 3.8 (pre-release), 66 bytes

```
lambda n:[s:="#"*(n+1-(k:=n%2))+" -"*(1-k)*n,"#"*(n+k)+" -"*k*n,s]

```

Outputs a list of lines, which is allowed by default I/O method rules.

Could 100% be shorter in some way.

Try it online!
> 1 votes

# Answer
# APL+WIN, 42 bytes

Prompts for n

```
⊃¯3↑(2|n)⌽4⍴(n⍴'#')(((n+1)⍴'#'),(n←⎕)⍴'-')

```

Try it online! Thanks to Dyalog Classic
> 1 votes

# Answer
# x86-64 machine code, 34 bytes

```
89 F0 D1 E8 99 B0 23 89 F1 F3 AA 72 0A AA 89 F1 66 B8 20 2D 66 F3 AB F5 B0 0A AA FF C2 7B E6 88 37 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the number n in ESI.

In assembly:

```
f:  mov eax, esi    # Set EAX to n.
    shr eax, 1      # Shift it right by 1. The low bit goes into CF.
    cdq             # Set EDX to 0 (as the high bit of EAX is 0).
r:  mov al, 0x23    # Set AL to the ASCII code of #.
    mov ecx, esi    # Set RCX to n (automatic zero extension).
    rep stosb       # Write AL to the string RCX times, advancing the pointer.
    jc s            # Jump if CF=1, to skip the guns.
    stosb           # Write AL to the string one more time, advancing the pointer.
    mov ecx, esi    # Set RCX to n (automatic zero extension).
    mov ax, 0x2D20  # Set AL and AH to the ASCII codes of the space and the hyphen.
    rep stosw       # Write those to the string RCX times, advancing the pointer.
s:  cmc             # Invert CF.
    mov al, 0x0A    # Set AL to the ASCII code of the line feed.
    stosb           # Write AL to the string, advancing the pointer.
    inc edx         # Add 1 to EDX, setting the flags except CF.
    jpo r           # Jump to repeat if the sum of the low 8 bits is odd.
                    # This is true for 1 (1₂) and 2 (10₂) but not for 3 (11₂).
    mov [rdi], dh   # Add the second-lowest byte of EDX, which is 0, to the string.
    ret             # Return.

```
> 1 votes

# Answer
# Lua, 69 bytes

```
n=...for i=1,3 do b=n+i print(("#"):rep(b%2+n)..(' -'):rep(b%2*n))end

```

Attempt This Online!

### Alternate Approaches

```
-- 73 bytes
a,n="#",...r=a.rep for i=1,3 do b=n+i print(r(a,n+b%2)..r(' -',b%2*n))end

```

```
-- 73 bytes as well
a,n="#",...for i=1,3 do b=n+i print(a:rep(n+b%2)..(' -'):rep(n*(b%2)))end

```

```
-- 73 bytes also as well
a,n="#",...for i=1,3 do print(a:rep(n+(n+i)%2)..(' -'):rep(n*(n+i%2)))end

```

```
-- 71 bytes with rearranging
a,n="#",...for i=1,3 do b=n+i print(a:rep(b%2+n)..(' -'):rep(b%2*n))end

```
> 1 votes

# Answer
# MathGolf, 19 bytes

```
)'#*û -k*+_k<kÄ\┼ßn

```

Try it online.

**Explanation:**

```
)          # Increase the (implicit) input-integer by 1
 '#*      '# Pop and push a string of that many "#"
    û -    # Push string " -"
       k*  # Repeat it the input amount of times as string
         + # Append the two strings together
_          # Duplicate the string
 k         # Push the input-integer
  <        # Only leave that many leading characters from the duplicated string
k          # Push the input-integer again
 Ä         # Loop that many times, with a single char as inner code-block:
  \        #  Swap the top two values
           # (basically swap for even values; and not for odd)
   ┼       # Push a copy of the second top item of the stack to the top
    ß      # Wrap all three values onto a list
     n     # Join by newlines
           # (after which the entire stack is output implicitly)

```
> 0 votes

# Answer
# Ruby, 36 bytes

```
->n{([?#*-~n+" -"*n,?#*n]*2)[n%2,3]}

```

Try it online!
> 0 votes

# Answer
# C#, 118 bytes

```
n=>string.Join('\n',new int[3].Select((_,i)=>new string('#',n)+(n%2==i%2?"#"+new string('x',n).Replace("x"," -"):"")))

```

*-5 bytes thanks to Stone\_Red from The Programmers Hangout discord*

Curse you C# and your verbose string repeating *shakes fist*

Try it on .NETFiddle

## Explanation

`n` is the size of the spaceship, `i` is the 0-indexed current line being generated.

`Select` is C#'s version of a `map` function. When the provided predicate takes 2 arguments, the first will be the original value in the collection being enumerated, and the second will be the index of that value in the collection.

In our case we don't care about the original value, we're just using it as a shorter `for(int i = 0; i < 3; i++)`. Likewise we don't care about the original type, because `Select` will return a collection of whatever type the provided predicate function returns. In this case the predicate function returns a string, so `Select` will return an `IEnumerable<string>` regardless of the fact that it's enumerating over an `int[]`. `int` was chosen as it's the shortest standard type name in .NET.

Every line of output begins with `new string('#',n)`, which is C#'s way to repeat a char `n` times. Then the following ternary statement handles generating guns:

```
(n%2==i%2?"#"+new string('x',n).Replace("x"," -"):"")

```

The condition here is `n%2==i%2`, which is true if the parity of the size and line number match. If `n`'s parity matches `i`'s parity, it's a gun line (even values for `n` will have a gun on line 0 and 2, odd values will have a gun on line 1).

Guns have one extra `#`, so we start with `"#"+`.
`new string('x',n).Replace("x"," -")` generates a string of `n` `x` characters, then replaces each `x` with  `-`, this is the golfiest way I know of to repeat a *string* `n` times, as the `new string('#',n)` method only works for repeating a single char.

Finally the `IEnumerable<string>` returned from `Select` is passed to `string.Join('\n',...)`, which simply concatenates the collection into a single string, with newlines between each line.
> 0 votes

# Answer
# Pip, 26 bytes

```
'#Xa.('#.'-XaJs)X%aBX^UhJn

```

Attempt This Online!

### Explanation

```
'#Xa.('#.'-XaJs)X%aBX^UhJn
                       h    Builtin variable for 100
                      U     Increment to 101
                     ^      Split into [1; 0; 1]
                   BX       Bitwise XOR each with
                 %a         Input mod 2
     (         )X           Repeat the following string that many (0 or 1) times:
      '#.                     Pound sign concatenated to
         '-Xa                 Hyphen repeated (input) times
             Js               Join on spaces
    .                       Concatenate the following to the beginning:
'#Xa                          Pound sign repeated (input) times
                        Jn  Join the final list on newlines and autoprint

```
> 0 votes

# Answer
# Retina 0.8.2, 47 bytes

```
.+
$*##$&$*-$&$*__
$
¶$`_¶$`
#-+(__)+\b|_

-
 -

```

Try it online! Link includes test cases. Explanation:

```
.+
$*##$&$*-$&$*__

```

Assume each row has a gun, so output the right number of `#`s and `-`s appropriately. Also append the same number of `_`s as `#`s for calculation purposes.

```
$
¶$`_¶$`

```

Triplicate the row but append an extra `_` to the middle row.

```
#-+(__)+\b|_

```

Delete the gun if it's on the wrong row(s).

```
-
 -

```

Space out the bullets.
> 0 votes

# Answer
# C (gcc), 98 bytes

```
r,d,k;f(n){for(r=4;--r;puts("")){for(k=n+r&1,d=n+k;d--;printf("#"));for(;k&&++d<n;printf(" -"));}}

```

Try it online!
> 0 votes

# Answer
# JavaScript (V8), 68 bytes

```
n=>[1,2,1].map(i=>'#'.repeat(n+(m=n+i&1))+' -'.repeat(m&&n)).join`
`

```

Try it online!
> 0 votes

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Standardize the Samples (Compute the z-Score)
Given a list of floating point numbers, *standardize it*.

### Details

* A list \\$x\_1,x\_2,\ldots,x\_n\\$ is *standardized* if the *mean* of all values is 0, and the *standard deviation* is 1. One way to compute this is by first computing the mean \\$\mu\\$ and the standard deviation \\$\sigma\\$ as $$ \mu = \frac1n\sum\_{i=1}^n x\_i \qquad \sigma = \sqrt{\frac{1}{n}\sum\_{i=1}^n (x\_i -\mu)^2} ,$$ and then computing the standardization by replacing every \\$x\_i\\$ with \\$\frac{x\_i-\mu}{\sigma}\\$.
* You can assume that the input contains at least two distinct entries (which implies \\$\sigma \neq 0\\$).
* Note that some implementations use the sample standard deviation, which is not equal to the population standard deviation \\$\sigma\\$ we are using here.
* There is a CW answer for all trivial solutions.

### Examples

```
[1,2,3] -> [-1.224744871391589,0.0,1.224744871391589]
[1,2] -> [-1,1]
[-3,1,4,1,5] -> [-1.6428571428571428,-0.21428571428571433,0.8571428571428572,-0.21428571428571433,1.2142857142857144]

```

(These examples have been generated with this script.)

# Answer
> 8 votes
# , ~~51~~ ~~45~~ ~~38~~ 37 bytes

Thanks to Giuseppe and J.Doe!

```
function(x)scale(x)/(1-1/sum(x|1))^.5

```

Try it online!

# Answer
> 5 votes
# CW for all trivial entries

---

## Python 3 \+ scipy, 31 bytes

```
from scipy.stats import*
zscore

```

Try it online!

# Octave / MATLAB, 15 bytes

```
@(x)zscore(x,1)

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Classic), ~~21~~ ~~20~~ 19 bytes

```
(-÷.5*⍨⊢÷⌹×≢)+/-⊢×≢

```

Try it online!

`⊢÷⌹` is sum of squares

`⊢÷⌹×≢` is sum of squares divided by length

# Answer
> 4 votes
# APL+WIN, ~~41,32~~ 30 bytes

9 bytes saved thanks to Erik + 2 more thanks to ngn

```
x←v-(+/v)÷⍴v←⎕⋄x÷(+/x×x÷⍴v)*.5

```

Prompts for vector of numbers and calculates mean standard deviation and standardised elements of input vector

# Answer
> 4 votes
# MATL, 10 bytes

```
tYm-t&1Zs/

```

Try it online!

### Explanation

```
t       % Implicit input
        % Duplicate
Ym      % Mean
-       % Subtract, element-wise
t       % Duplicate
&1Zs    % Standard deviation using normalization by n
/       % Divide, element-wise
        % Implicit display

```

# Answer
> 3 votes
# \+ pryr, ~~53~~ 52 bytes

-1 byte using `sum(x|1)` instead of `length(x)` as seen in @Robert S.'s solution

```
pryr::f((x-(y<-mean(x)))/(sum((x-y)^2)/sum(x|1))^.5)

```

For being a language built for statisticians, I'm amazed that this doesn't have a built-in function. At least not one that I could find. Even the function `mosaic::zscore` doesn't yield the expected results. This is likely due to using the population standard deviation instead of sample standard deviation.

Try it online!

# Answer
> 3 votes
# Tcl, 126 bytes

```
proc S L {lmap c $L {expr ($c-[set m ([join $L +])/[set n [llength $L]].])/sqrt(([join [lmap c $L {expr ($c-$m)**2}] +])/$n)}}

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~33~~ 29 bytes

```
{d÷.5*⍨l÷⍨+/×⍨d←⍵-(+/⍵)÷l←≢⍵}

```

*-4 bytes thanks to @ngn*

Try it online!

# Answer
> 2 votes
# Jelly, 10 bytes

```
_ÆmµL½÷ÆḊ×

```

Try it online!

It's not any shorter, but Jelly's determinant function `ÆḊ` also calculates vector norm.

```
_Æm             x - mean(x)
   µ            then:
    L½          Square root of the Length
      ÷ÆḊ       divided by the norm
         ×      Multiply by that value

```

# Answer
> 2 votes
# Mathematica, 25 bytes

```
Mean[(a=#-Mean@#)a]^-.5a&

```

Pure function. Takes a list of numbers as input and returns a list of machine-precision numbers as output. Note that the built-in `Standardize` function uses the sample variance by default.

# Answer
> 2 votes
# , 22 bytes

-1 byte thanks to Cows quack!

```
(-%[:%:1#.-*-%#@[)+/%#

```

Try it online!

# , 31 23 bytes

```
(-%[:%:#@[%~1#.-*-)+/%#

```

Try it online!

```
                   +/%# - mean (sum (+/) divided (%) by the number of samples (#))
(                 )     - the list is a left argument here (we have a hook)
                 -      - the difference between each sample and the mean
                *       - multiplied by
               -        - the difference between each sample and the mean
            1#.         - sum by base-1 conversion
          %~            - divided by
       #@[              - the length of the samples list
     %:                 - square root
   [:                   - convert to a fork (function composition)
 -                      - subtract the mean from each sample
  %                     - and divide it by sigma

```

# Answer
> 2 votes
# Haskell, ~~80~~ ~~75~~ 68 bytes

```
t x=k(/sqrt(f$sum$k(^2)))where k g=g.(-f(sum x)+)<$>x;f=(/sum(1<$x))

```

Thanks to @flawr for the suggestions to use `sum(1<$x)` instead of `sum[1|_<-x]` and to inline the mean, @xnor for inlining the standard deviation and other reductions.

Expanded:

```
-- Standardize a list of values of any floating-point type.
standardize :: Floating a => [a] -> [a]
standardize input = eachLessMean (/ sqrt (overLength (sum (eachLessMean (^2)))))
  where

    -- Map a function over each element of the input, less the mean.
    eachLessMean f = map (f . subtract (overLength (sum input))) input

    -- Divide a value by the length of the input.
    overLength n = n / sum (map (const 1) input)

```

# Answer
> 2 votes
# MathGolf, 7 bytes

```
▓-_²▓√/

```

Try it online!

## Explanation

This is literally a byte-for-byte recreation of Kevin Cruijssen's 05AB1E answer, but I save some bytes from MathGolf having 1-byters for everything needed for this challenge. Also the answer looks quite good in my opinion!

```
▓         get average of list
 -        pop a, b : push(a-b)
  _       duplicate TOS
   ²      pop a : push(a*a)
    ▓     get average of list
     √    pop a : push(sqrt(a)), split string to list
      /   pop a, b : push(a/b), split strings

```

# Answer
> 1 votes
# Jelly, 10 bytes

```
_Æm÷²Æm½Ɗ$

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES7),  ~~80~~  79 bytes

```
a=>a.map(x=>(x-g(a))/g(a.map(x=>(x-m)**2))**.5,g=a=>m=eval(a.join`+`)/a.length)

```

Try it online!

### Commented

```
a =>                      // given the input array a[]
  a.map(x =>              // for each value x in a[]:
    (x - g(a)) /          //   compute (x - mean(a)) divided by
    g(                    //   the standard deviation:
      a.map(x =>          //     for each value x in a[]:
        (x - m) ** 2      //       compute (x - mean(a))²
      )                   //     compute the mean of this array
    ) ** .5,              //   and take the square root
    g = a =>              //   g = helper function taking an array a[],
      m = eval(a.join`+`) //     computing the mean
          / a.length      //     and storing the result in m
  )                       // end of outer map()

```

# Answer
> 1 votes
# Charcoal, ~~25~~ 19 bytes

```
≧⁻∕ΣθＬθθＩ∕θ₂∕ΣＸθ²Ｌθ

```

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

```
       θ    Input array
≧           Update each element
 ⁻          Subtract
   Σ        Sum of
    θ       Input array
  ∕         Divided by
     Ｌ      Length of
      θ     Input array

```

Calculate \\$\mu\\$ and vectorised subtract it from each \\$x\_i\\$.

```
  θ         Updated array
 ∕          Vectorised divided by
   ₂        Square root of
     Σ      Sum of
       θ    Updated array
      Ｘ     Vectorised to power
        ²   Literal 2
    ∕       Divided by
         Ｌ  Length of
          θ Array
Ｉ           Cast to string
            Implicitly print each element on its own line.

```

Calculate \\$\sigma\\$, vectorised divide each \\$x\_i\\$ by it, and output the result.

Edit: Saved 6 bytes thanks to @ASCII-only for a) using `SquareRoot()` instead of `Power(0.5)` b) fixing vectorised `Divide()` (it was doing `IntDivide()` instead) c) making `Power()` vectorise.

# Answer
> 1 votes
# K (oK), 33 23 bytes

-10 bytes thanks to ngn!

```
{t%%(+/t*t:x-/x%#x)%#x}

```

Try it online!

First attempt at coding (I don't dare to name it "golfing") in K. I'm pretty sure it can be done much better (too many variable names here...)

# Answer
> 1 votes
# Python 3 \+ numpy, 46 bytes

```
lambda a:(a-mean(a))/std(a)
from numpy import*

```

Try it online!

# Answer
> 1 votes
# Haskell, 59 bytes

```
(%)i=sum.map(^i)
f l=[(0%l*y-1%l)/sqrt(2%l*0%l-1%l^2)|y<-l]

```

Try it online!

Doesn't use libraries.

The helper function `%` computes the sum of `i`th powers of a list, which lets us get three useful values.

* `0%l` is the length of `l` (call this `n`)
* `1%l` is the sum of `l` (call this `s`)
* `2%l` is the sum of squares of `l` (call this `m`)

We can express the z-score of an element `y` as

```
(n*y-s)/sqrt(n*v-s^2)

```

(This is the expression `(y-s/n)/sqrt(v/n-(s/n)^2)` simplified a bit by multiplying the top and bottom by `n`.)

We can insert the expressions `0%l`, `1%l`, `2%l` without parens because the `%` we define has higher precedence than the arithmetic operators.

`(%)i=sum.map(^i)` is the same length as `i%l=sum.map(^i)l`. Making it more point-free doesn't help. Defining it like `g i=...` loses bytes when we call it. Although `%` works for any list but we only call it with the problem input list, there's no byte loss in calling it with argument `l` every time because a two-argument call `i%l` is no longer than a one-argument one `g i`.

# Answer
> 1 votes
# Pyth, ~~21~~ 19 bytes

```
mc-dJ.OQ@.Om^-Jk2Q2

```

Try it online here.

```
mc-dJ.OQ@.Om^-Jk2Q2Q   Implicit: Q=eval(input())
                       Trailing Q inferred
    J.OQ               Take the average of Q, store the result in J
           m     Q     Map the elements of Q, as k, using:
             -Jk         Difference between J and k
            ^   2        Square it
         .O            Find the average of the result of the map
        @         2    Square root it
                       - this is the standard deviation of Q
m                  Q   Map elements of Q, as d, using:
  -dJ                    d - J
 c                       Float division by the standard deviation
                       Implicit print result of map

```

*Edit: after seeing Kevin's answer, changed to use the average builtin for the inner results. Previous answer: `mc-dJ.OQ@csm^-Jk2QlQ2`*

# Answer
> 1 votes
# MATLAB, 26 bytes

Trivial-ish, `std(,1)` for using population standard deviation

```
f=@(x)(x-mean(x))/std(x,1)

```

# Answer
> 1 votes
# TI-Basic (83 series), ~~14~~ 11 bytes

```
Ans-mean(Ans
Ans/√(mean(Ans²

```

Takes input in `Ans`. For example, if you type the above into `prgmSTANDARD`, then `{1,2,3}:prgmSTANDARD` will return `{-1.224744871,0.0,1.224744871}`.

Previously, I tried using the `1-Var Stats` command, which stores the population standard deviation in `σx`, but it's less trouble to compute it manually.

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
ÅA-DnÅAt/

```

Port of *@Arnauld*'s JavaScript answer, so make sure to upvote him!

Try it online or verify all test cases.

**Explanation:**

```
ÅA          # Calculate the mean of the (implicit) input
            #  i.e. [-3,1,4,1,5] → 1.6
  -         # Subtract it from each value in the (implicit) input
            #  i.e. [-3,1,4,1,5] and 1.6 → [-4.6,-0.6,2.4,-0.6,3.4]
   D        # Duplicate that list
    n       # Take the square of each
            #  i.e. [-4.6,-0.6,2.4,-0.6,3.4] → [21.16,0.36,5.76,0.36,11.56]
     ÅA     # Pop and calculate the mean of that list
            #  i.e. [21.16,0.36,5.76,0.36,11.56] → 7.84
       t    # Take the square-root of that
            #  i.e. 7.84 → 2.8
        /   # And divide each value in the duplicated list with it (and output implicitly)
            #  i.e. [-4.6,-0.6,2.4,-0.6,3.4] and 2.8 → [-1.6428571428571428,
            #   -0.21428571428571433,0.8571428571428572,-0.21428571428571433,1.2142857142857144]

```

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

```
	DEFINE('Z(A)')
Z	X =X + 1
	M =M + A<X>	:S(Z)
	N =X - 1.
	M =M / N
D	X =GT(X) X - 1	:F(S)
	A<X> =A<X> - M	:(D)
S	X =LT(X,N) X + 1	:F(Y)
	S =S + A<X> ^ 2 / N	:(S)
Y	S =S ^ 0.5
N	A<X> =A<X> / S
	X =GT(X) X - 1	:S(N)
	Z =A	:(RETURN)

```

Try it online!

Link is to a functional version of the code which constructs an array from STDIN given its length and then its elements, then runs the function `Z` on that, and finally prints out the values.

Defines a function `Z` which returns an array.

The `1.` on line 4 is necessary to do the floating point arithmetic properly.

# Answer
> 1 votes
# Julia 0.7, 37 bytes

```
a->(a-mean(a))/std(a,corrected=false)

```

Try it online!

# Answer
> 1 votes
# Factor, 34 bytes

```
[ dup demean swap 0 std-ddof v/n ]

```

Try it online!

Sadly, while Factor has the `z-score` word, it uses the sample standard deviation instead of the population standard deviation.

---
Tags: code-golf, math, array, arithmetic, statistics
---