title: Read a password

text:
# Question
Title: Read a password
Your challenge is to read a "password" from the keyboard / standard input.

**Challenge**:

* Read a string `s` invisibly.
* For each of the characters in `s`, print a character `c`.
* In realtime.

**Rules:**

* You must print `c` in realtime. As soon as the user enters a character you must display `c`.
* `c` must be constant, i.e. it must be the same character.
* `c` can be any *visible* character (i.e. it cannot be a newline, space, tab, or unprintable).
* `c` can't be based on `s`, i.e. `c` must be defined/constant before `s` is read.
* `c` must be the same every time the program is run.
* `c` can be one of the characters in `s` if by accident, as long as all other rules are followed.
* None of the characters of `s` may appear on the screen, `c` excepted (see previous rule).
* You may use any reasonable methods of input and output as long as all other rules are followed.
* You may assume that the length of `s` is never longer than the terminal/graphical window width.
* If using a terminal, your program should terminate after a newline or EOF is entered.

**Example**:

If `s` was `password01` and `c` was `*`, the output would look something like:

**Winner**:

The shortest submission in each language wins.

# Answer
> 6 votes
# str, 5 bytes

```
n=?,1

```

Due to a bug, this is 5 bytes. It should be only 1 byte:

```
1

```

# Answer
> 21 votes
# HTML, 20 bytes

```
<input type=password
```

---

## Alternative: HTML + JavaScript, 51 bytes

Although the OP has confirmed that to be valid, here's a solution using JS for the purists!

```
<input id=i oninput=i.value=i.value.replace(/./g,8)
```

# Answer
> 10 votes
# Vim, 36 bytes:

```
:im <C-v><CR> <C-v><esc>ZQ<CR>:au I<tab><tab> * let v:char=0<CR>i

```

This uses *vim-key notation*, so `<C-v>` is *control-v*, `<CR>` is enter, `<esc>` is the escape key, and `<tab>` is the tab key.

*c* is `'0'`.

Here is a hexdump to prove the byte count is accurate:

```
00000000: 3a69 6d20 160a 2016 1b5a 510a 3a61 7520  :im .. ..ZQ.:au
00000010: 4909 0920 2a20 6c65 7420 763a 6368 6172  I.. * let v:char
00000020: 3d30 0a69                                =0.i

```

This works by running the following two ex commands:

```
:imap <CR> <esc>ZQ
:autocmd InsertCharPre * let v:char=0

```

The first one means

```
:imap               " Anytime the following is pressed in insert mode:
      <CR>          "   (the 'enter' key)
           <esc>ZQ  " Then act as if the user instead pressed '<esc>ZQ' (close the buffer)

```

And the second one means

```
:autocmd                                " Automatically as vim runs:
         InsertCharPre                  "   Any time the user is about to insert a char
                       *                "   In any type of file
                         let v:char=0   "     Then instead insert a '0' character

```

# Answer
> 9 votes
# Ruby with Shoes, 29 characters

```
Shoes.app{edit_line secret:1}

```

Sample output:

# Answer
> 6 votes
# Aceto, ~~8~~ ~~7~~ 6 bytes

```
,!`XpO

```

### Explanation:

Read a character (`,`), negate it (`!`) and conditionally exit. Print the zero on top of the stack (`p`) and go back to the beginning.

Run with `-F` to see the effect immediately (because flushing)

My first solution was based on the sandbox post, with spaces allowed as replacement characters and no need to exit on enter (4 bytes):

```
,'p>

```

# Answer
> 5 votes
# C on POSIX, ~~128~~ ~~117~~ ~~113~~ 96 bytes

-11 thanks to Quentin searching through `termios.h`
-4 thanks to Quentin pointing out my stupid mistakes
-17 because Quentin is a freaking wizard.

```
c,t[15];f(){for(tcgetattr(1,t),t[3]&=~10,tcsetattr(1,0,t);(c=getchar())^10&&c^4;)printf(".");}

```

This puts STDIN into raw/invisible mode so that it can get keypresses in realtime. This takes 77 bytes and I'm sure I can golf it in a bit. **Note that this does not reset STDIN upon exiting so it will mess up your terminal if you don't do so manually.**

Here's how you can reset STDIN:

```
void stdin_reset(void)
{
    struct termios t;
    get_stdin(&t);
    t.c_lflag |= ECHO;
    t.c_lflag |= ICANON;
    set_stdin(&t);
}

```

Output as shown in the GIF :-)

# Answer
> 4 votes
# x86 machine code on MS-DOS - 14 bytes

As usual, this is a full COM file, that can be run on DosBox, plus most DOS variants.

```
00000000  b4 08 b2 2a cd 21 80 f4  0a 3c 0d 75 f7 c3        |...*.!...<.u..|
0000000e

```

Commented assembly:

```
    org 100h

section .text

start:
    mov ah,8h       ; ah starts at 08h (read console, no echo)
    mov dl,'*'      ; write asterisks (we could have left whatever
                    ; startup value we have here, but given that dx=cs,
                    ; we have no guarantee to get a non-zero non-space
                    ; value)
lop:
    ; this loop runs twice per character read: the first time with
    ; ah = 08h (read console, no echo syscall), the second time with
    ; ah = 02h (write console); a xor is used to switch from one
    ; mode to the other
    int 21h         ; perform syscall
    xor ah,0ah      ; switch syscall 08h <=> 02h
    cmp al,0dh      ; check if we read a newline (if we wrote stuff
                    ; we are just checking the last value read, so
                    ; no harm done; at the first iteration al starts
                    ; at 0, so no risk here)
    jne lop         ; loop if it wasn't a newline
quit:
    ret             ; quit

```

# Answer
> 3 votes
# Python 2, 50 bytes

```
from msvcrt import*
while'\r'!=getch():print'\b*',

```

Only works on windows

# Answer
> 3 votes
# Java 5-8, ~~125~~ ~~122~~ ~~131~~ 124 bytes

```
class X{public static void main(String[]a){new java.awt.Frame(){{add(new javax.swing.JPasswordField());setVisible(1>0);}};}}

```

# Ungolfed:

```
class X{
    public static void main(String[]a){
        new java.awt.Frame(){
            {
                add(new javax.swing.JPasswordField());
                setVisible(1>0);
            }
        };
    }
}

```

# Result:

# Credit:

*-3 @MD XF (Pointed out my stupid mistake with `String[]args`)*

*-7 @KritixiLithos (Pointed out `public class` can just be `class`)*

# Answer
> 3 votes
# AHK, 17 bytes

```
InputBox,o,,,HIDE

```

Built-ins are not interesting.

# Answer
> 3 votes
# Mathematica 34 bytes

```
 InputString["",FieldMasked->True];

```

An single asterisk appears, after each character is keyed in. The empty quotation marks are for the title that appears in the pop-up input window.

The `;` prevents the password from being printed.

# Answer
> 3 votes
# Forth (gforth), 54 bytes

```
: f begin key dup 4 - swap 13 - * while ." *" repeat ;

```

### Explanation

```
begin      \ enters the loop
    key    \ waits for a single character as input, places ascii code of character on stack
    dup    \ duplicates the key value on the stack
    4 -    \ subtracts 4 from the key value (shorter way of checking for not equals)
    swap   \ swaps the top two stack values
    13 -   \ subtract 13 from the key value
    *      \ multiply top two stack values (shorter version of "and")
while      \ if top of stack is true, enter loop body, else exit loop
    ." *"  \ output *
repeat     \ go back to beginning of loop

```

# Answer
> 2 votes
# Vim, ~~58~~ ~~50~~ ~~52~~ 50 bytes

Added to make sure it handled spaces properly.

Thanks to @DJMcMayhem for a bunch of help and ideas

```
i:im 32 *Y94pVGg
kWcW<Space>
:im
 ZQ
dG@"qi

```

In typical Vim key syntax below. The characters marked like with a `^` are `Ctrl+<char>`, so `^Q`=`Ctrl+q`

```
i:im ^V^V32 *^[Y94pVGg^A
kWcW<Space>^[
:im ^V
 ZQ
dG@"qi

```

There's no TIO link, because you'd need to directly input to Vim (as opposed to pre-inputting like normal). To run the code you need to type it into Vim, and then you can type your password and hit enter. It won't do anything with the password. It won't even know what it was. As soon as you hit enter the Vim window will `:q!`

This works by mapping all printable ASCII to `*` in insert mode, and mapping `<CR>` to `<ESC>:q!<CR>`

# Answer
> 2 votes
# FLTK, 47 characters

```
Function{}{}{Fl_Window{}{}{Fl_Input{}{type 5}}}

```

Sample run:

```
bash-4.4$ fluid -c password.fl

bash-4.4$ fltk-config --compile password.cxx
g++ -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -o 'password' 'password.cxx' -Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -lfltk -lX11

bash-4.4$ ./password

```

Sample output:

# Answer
> 2 votes
# Processing, 53 bytes

```
String a="";void draw(){text(keyPressed?a+=0:a,9,9);}

```

This takes input via keypresses from a graphical window. The character it chooses to represent passwords with is `0`. Note that due to the high framerate, each keypress will appear as multiple `0`s (and also due to the fact that this is `keyPressed` and not `keyTyped` (not a boolean) or `keyrelease`).

# Answer
> 2 votes
# Bash, 54 bytes

```
while read -eN1 c 2>&-;[[ ${c/$'\r'/} ]];do printf X;done

```

For scoring purposes, `$'\r'` can be replaced with a literal carriage return.

Try it online! (not much to look at)

# Answer
> 2 votes
## ZX81 BASIC, 54 bytes

```
10 IF LEN INKEY$ THEN GOTO PI
30 IF NOT LEN INKEY$ THEN GOTO EXP PI
50 IF INKEY$>"Z" THEN STOP
70 PRINT "*";
90 GOTO PI

```

In the ZX81 character set the printable characters are in the range space to `Z`, although you can't actually input a space this way as it's the break character.

## ZX Spectrum BASIC, 24 bytes

```
10 PAUSE NOT PI: IF INKEY$>=" " THEN PRINT "*";:GOTO PI

```

Note that `>=` counts as a single-byte keyword in Sinclair BASIC (codepoint 140 in this case).

# Answer
> 2 votes
# R, 29 bytes

```
invisible(openssl::askpass())

```

Built-in that handles password entries. Opens a new window and replaces the input with dots. `invisible` is used to suppress printing the password to STDOUT.

# Answer
> 2 votes
# Tcl/Tk, 18

```
gri [ent .e -sh *]

```

Must be run on the in the interactive shell (or have abbreviations enabled):

# Answer
> 2 votes
# Vim, 15 keystrokes

```
:cal inp<S-tab>'')|q<cr>

```

`<S-tab>` means `shift + tab`.

Apparently, there is a builtin for this that I wasn't aware of. Since I really like my manual answer, and this approach is radically different, I figured I should post a new answer instead of editing.

This works by calling the `inputsecret` function, then immediately quitting after it exits.

# Answer
> 2 votes
# 6502 machine code (C64), ~~22~~ 21 bytes

```
0e 08 20 9f ff 20 e4 ff f0 f8 c9 0d f0 01 a9 60 20 d2 ff 50 ed

```

**Usage**: `SYS 2062`

Commented disassembly listing (ACME), you can uncomment the first three commented lines to launch with `RUN` once loaded:

```
!cpu 6502
!to "password2.prg",cbm
;* = $0801                               ; BASIC starts at #2049
;!byte $0d,$08,$dc,$07,$9e,$20,$32,$30   ; BASIC to load $c000
;!byte $36,$32,$00,$00,$00               ; inserts BASIC line: 2012 SYS 2062

    GETIN  =  $FFE4
    SCNKEY =  $FF9F
    CHROUT =  $FFD2

* = $080e
keyScan:
    jsr SCNKEY  ; get key
    jsr GETIN   ; put key in A

    beq keyScan ; if no key pressed loop

    cmp #13     ; check if RETURN was pressed
    beq $081b   ; if true go to operand of next instruction (#$60 = rts)

    lda #$60    ; load char $60 into accumulator
    jsr CHROUT  ; print it

    bvc keyScan ; loop

```

Comments:

* I haven't found anything in the docs, but it seems that, after the GETIN call, beq branches only where no new key presses have been recorded;
* Using #$60 as output char, that byte can be reused as "rts" instruction when RETURN is pressed.

# Answer
> 1 votes
# Python 3 + `tkinter` \- ~~63~~ 61 bytes

```
from tkinter import*
t=Tk();Entry(show=1).pack();t.mainloop()

```

Displays a `1` for every character, ends when closing window (OP said it's allowed).

# Answer
> 1 votes
# Groovy, ~~77~~ 73 bytes

```
{new java.awt.Frame(){{add(new javax.swing.JPasswordField());visible=1}}}

```

*This is an anonymous closure, with 0 required inputs.*

# Ungolfed:

```
{
    new java.awt.Frame() {
        {
            add(new javax.swing.JPasswordField())
            visible=1
        }
    }
}

```

---

*Edit 1 (-4 bytes): Component#visible can be directly accessed, read more here.*

# Answer
> 1 votes
# Micro, 35 bytes

```
"":i{L46c:\
i~+:i
i10c=if(,a)}a
i:\

```

## explination:

```
"":i                      create new blank string 'i'
    {                          begin input loop
     L                         input a character
      46c:\                    display ascii char #46 (.) (it is popped, leaving the input char from 'L'
           i~+:i               push i, flip i and the char around, concatinate them, and store that to i
                i10c=if(,a)}a  OK, a lot happens here, if a NL is in i, the loop terminates, and the final i:\ will display the input

```

# Answer
> 1 votes
## BF, 24 bytes

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

```

Works with bf.doleczek.pl. You can send a zero char to the program with Ctrl+Z.

Alternative solution:

## BF, 1 byte

```
,

```

This is a very tongue-in-cheek solution. My terminal is **0 characters** wide, so please don't enter any passwords longer than that.

# Answer
> 1 votes
## PowerShell, 12 bytes

```
Read-Host -a

```

This reads input from host and, with the -a flag treats it as a securestring/password. In the ISE it pops up a message box which has a similar behavior since the ISE doesn't allow keypress capture.

```
PS C:\Windows\system32> Read-Host -a
************

```

# Answer
> 1 votes
# brainfuck, 21 bytes

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

```

Last one, I promise. No input = -1, end of input = 0

### How it Works

```
-[  Enters the loop
  +>, Get input
     [<->+ If not end of input it create the ÿ character and check if the input is not -1
          [<.>[-]]] If there was input, print the ÿ character.
                    <] Exit the loop if end of input

```

# Answer
> 1 votes
# QBasic, 48 bytes

```
DO
a$=INPUT$(1)
IF ASC(a$)=13THEN END
?"*";
LOOP

```

`INPUT$(1)` reads the next character from keyboard input. (This can include things like tab, backspace, and escape, but since the OP didn't say anything about those I'll assume we don't have to worry about them.) If the character is `\r` (ASCII 13), terminate the program; otherwise, print `*` without a newline. Repeat ad infinitum.

# Answer
> 1 votes
## Perl + Bash, 30 bytes

```
print"*"while$|=1+`read -sn 1`

```

`c` is `*`, uses `read` from bash, so isn't a pure Perl solution.

# Answer
> 0 votes
# QBIC, 44 bytes

```
{X=inkey$~X<>@`|~X=chr$(13)|_X\Y=Y+@*`_C?Y

```

## Explanation

```
{            DO
X=inkey$     Read a char, set it to X$
             Note that INKEY$ doesn't wait for keypress, but simply sends out "" if no key was pressed.
~X<>@`|      IF X$ has a value THEN
~X=chr$(13)| IF that value is ENTER
_X           THEN END
\            ELSE
Y=Y+@*`      append a literal * to Y$
_C           Clear the screen
?Y           Display Y$ (having 1 * for each char entered)
             The IF's and the DO-loop are auto-closed at EOF{            DO

```

# Answer
> 0 votes
# Python 2 (\*nix only), 75 bytes

```
import sys,tty
i=sys.stdin
tty.setraw(i)
while i.read(1)!='\r':print'\b*',

```

(Warning: messes up your stdin and doesn't fix it, so maybe run in a screen instance if you don't want to have to restart your console).

Rod has a (shorter) Python 2 answer that only works on Windows - here's a Python 2 version that works on \*nix (and not Windows, I think)

# Answer
> 0 votes
# Befunge, 18 bytes

```
"**"~:!#@_0`!_ #,_

```

Enter a null byte to stop input

# Answer
> 0 votes
# \>\<\>, 10 bytes

```
"i:?!;1+?o

```

Try It Here

Enter a null byte to end input

# Answer
> 0 votes
# Aheui (esotope), 43 bytes

```
밣발따밯밧밧누
희）빠뫃쳐）뎌

```

Try it online!

Unfortunately, I couldn't find interactive Aheui interpreter. Aheui processer made with Javascript looks like somewhat interactive, but it doesn't print till input `!!!`. And input `!!!` just terminates program.

Many Aheui implementation put `-1` into stack when there are no more input, and this code checks if input is -1. If not, just print `)`, because its ascii code is 40, easy to make.

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


title: That's not my X, its Y is too Z

text:
# Question
Title: That's not my X, its Y is too Z
This challenge is inspired by a series of young children's books by Fiona Watt and Rachel Wells, which I've recently been enjoying with my daughter.

In each book a mouse (illustrated, but not part of the text) complains that a succession of 5 things of the same type are not its thing. It then backs this up by declaring that some component of the thing doesn't have the property it expects.

On the sixth time of asking, the mouse finds its thing and is pleased because it has the expected property.

Here is the text of a typical example:

```
That's not my bunny, its tail is too fluffy.
That's not my bunny, its paws are too rough.
That's not my bunny, its tail is too woolly.
That's not my bunny, its eyes are too shiny.
That's not my bunny, its nose is too wrinkled.
That's my bunny! Its ears are so soft.

```

Now, most programming folk would realise that this is a very algorithmic method of producing some text. Because it's such a clear process, we should be able to reproduce this by writing some code.

Let's start with three collections of words:

```
things = ["dinosaur", "lamb", "princess", "reindeer", "train"]
parts = ["back", "bells", "body", "bows", "crown", "dress", "ears",
  "engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
  "nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
  "tiara", "wheels", "windows"]
properties = ["bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
  "hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
  "soft", "sparkly", "squashy", "thick", "velvety", "woolly"]

```
* First, we decide which kind of thing we will be describing.
* Then 5 times, we will generate the line "That's not my \[thing\], its \[part\] is too \[property\].
* Finally, we generate the line "That's my \[thing\]! Its \[part\] is so \[property\]!

# The challenge

* Generate the text of a "That's not my..." story.
* It must not consistently reproduce the same text.
* It's code golf, so attempt to do so in the smallest number of bytes.
* Use any language you please.
* White space doesn't matter, but there must be a newline character between lines.
* The lists of source words are not part of your answer (in TIO they can be added to the header).
* You can rename the lists of source words.
* Output can be output to a terminal or text generated into an object.
* Please include a link to an online interpreter.
* Ignore plurals, "its horns is" is fine.
* It doesn't need to make sense. If your princess's funnel is too fluffy, just say so.

Sample output:

```
That's not my train, its engine is too rusty.
That's not my train, its hooves is too thick.
That's not my train, its sash is too fuzzy.
That's not my train, its tail is too velvety.
That's not my train, its horns is too glittery.
That's my train! Its hooves is so hairy.

```

Happy golfing!

# Answer
> 1 votes
# 05AB1E, 63 bytes

```
ΩU6F€Ω`XN5Qi“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“ë“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“}.ª,

```

Try it online.

**68 bytes version which doesn't output duplicated parts nor properties:**

```
ΩUε.r6£}øεXª`N5Qi“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“ë“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“}.ª,

```

Try it online.

Both programs assumes the list of things is the first input, and a list containing the list of parts and list of properties is the second input.

### Explanation:

```
Ω            # Pop and push a random element of the things-list
 U           # Pop and store it in variable `X`
  6F         # Loop 6 times:
    €Ω       #  Get a random element from both the parts and properties list
      `      #  Push them to the stack
       X     #  And also push variable `X`
             #  (the order on the stack is now: property, part, thing)
    N5Qi     #  If it's the last iteration:
        “€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“
            '#   Push dictionary string "that's my ÿ! its ÿ is so ÿ."
       ë     #  Else:
        “€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“
            '#   Push dictionary string "that's not my ÿ, its ÿ is too ÿ."
             #  (where the `ÿ` are automatically replaced with the words on the stack)
       }.ª   #  After the if-else: sentence-capitalize the strings
             #  (so the "That's " as well as the "! Its")
          ,  #  And output it with trailing newline

ΩU           # Pop and store a random thing in variable `X`
  ε          # Map the list of lists of parts/properties to:
   .r        #  Shuffle the list
     6£      #  And leave the first six elements
  }ø         # After the map: zip/transpose to create pairs of part & property
    ε        # Foreach over the pairs:
     `XN5Qi“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“ë“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“}.ª,
             #  And the rest of the code is the same as above

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“` is `"that's my ÿ! its ÿ is so ÿ."` and `“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“` is `"that's not my ÿ, its ÿ is too ÿ."`.

# Answer
> 10 votes
# Python 3, 149 bytes

```
lambda a,*l:shuffle(a)or["That's "+s%(a[0],*map(choice,l))for s in["not my %s, its %s is too %s."]*5+["my %s! Its %s is so %s."]]
from random import*

```

Try it online!

-9 bytes thanks to movatica

# Answer
> 8 votes
# Charcoal, 72 bytes

```
≔‽θθＦ⁵«That's not my θ, its ‽η is too ‽ζ.⸿»That's my θ! Its ‽η is so ‽ζ.

```

Try it online! Link is to verbose version of code. Expects the arrays of things, parts and properties to be in the variables `θ`, `η` and `ζ`, which is most easily arranged by providing them in the input rather than the header. Explanation:

```
≔‽θθ

```

Pick a random thing.

```
Ｆ⁵«That's not my θ, its ‽η is too ‽ζ.⸿»

```

Print five negative sentences.

```
That's my θ! Its ‽η is so ‽ζ.

```

Print the positive sentence.

# Answer
> 6 votes
# Japt v2.0a0 `-R`, 73 bytes

```
ö
6Æ`Tt's {`not `pT=Y<5}my {+`!,`gT} {73dT*H}ts {Vö}  {`tÑ?`ë2!T} {Wö}.

```

Takes the three lists as `U`, `V`, and `W`. Those are the default input variables anyways, so just put the three lists in the input section.

Try it

```
ö                         Saves the random object in variable U
6Æ                        Range [0..6), and map each to the following string
`That's                   The string "That's " plus
{`not `pT=Y<5}            "not " if the index is less than 5 (and store that in variable T), else ""
my                        Literal "my " plus
{+`!,`gT}                 U plus ',' if T, else '!'
{73dT*H}ts                "its " if T, else "Its "
{Vö}                      Random item from V
is
{`tsooo`ë2!T}             "too" if T, else "so"
{Wö}.                     Random item from V, plus a period

```

# Answer
> 6 votes
# PowerShell, 147 bytes

This main program will not repeat any part or property in a run, and has reasonable randomization.

```
$t=$l|Random
$a=$a|Random -c 6
$r=$r|Random -c 6
0..4|%{"That's not my $t, its $($a[$_]) is too "+$r[$_]}
"That's my $t! Its $($a[5]) is so "+$r[5]

```

Try it online!

Writing `get-random` so many times costs so many characters! However, unless you are willing to let parts and properties be repeated, I can't see a way to shrink this in powershell any further. Unless you move the first 3 line pipes to the end of the 3 assignment lines in the header. To have something like

```
# Header
$l = ("dinosaur", "lamb", "princess", "reindeer", "train")|Get-Random
$a = ("back", "bells", "body", "bows", "crown", "dress", "ears",
  "engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
  "nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
  "tiara", "wheels", "windows")|sort{Get-Random}
$r = ("bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
  "hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
  "soft", "sparkly", "squashy", "thick", "velvety", "woolly")|sort{Get-Random}

# Main
(1..5)|%{echo("That's not my $t, its "+$a[$_]+" is too "+$r[$_])}
"That's my $t! Its "+$a[6]+" is so "+$r[6]

```

But that seems like it's cheating, and still doesn't beat Neil's answer.

Edit: Thanks for the tips Matt, and thanks AdmBorkBork for fleshing them out, removing the 3 sets of `get-` text reduced it to 159 bytes, then some more golf from Adm got it down to 147. The code I was thinking of which allowed duplicates and contradictory statements was **144 characters** after applying the same golf tips.

```
function n{(random 18)+1}
$t=$l[(n)%5]
0..4|%{"That's not my $t, its $($a[(n)]) is too "+$r[(n)]}
"That's my $t! Its $($a[$(n)]) is so "+$r[(n)]

```

Try it online!

However, it not only has a tendency to say the same thing multiple times, but it pretty much requires that your inputs be the same number of elements. I believe the pseudo random number generator being used is heavily dependent on the clock, and quick repeated calls to it can often result in the same result. Then it has the condition that it only uses the whole list if all lists are the same length.With only saving 3~5 characters and having so many caveats, I prefer the code at the start of this post.

# Answer
> 4 votes
# Jelly, 72 bytes

```
XWWẋ6;X€}⁶pʋ€s5“ʠĖµʋb⁵J¥\¢wBD®-Ƥd(CḤ!²kT“Ø!1ẆÑ⁹ṁṾƤṛḄėÄṂMƓṾṖ¿O*½»Ỵ€¤żⱮ"ẎY

```

Try it online!

# Answer
> 2 votes
# JavaScript, 129

```
(a,b,c)=>(z='',a.forEach((f,i)=>z+=`That's ${q=i!=5?"not ":""}my ${f}${q?", i":"! I"}ts ${b[i]} is ${q?"to":"s"}o ${c[i]}.\n`),z)

```

input is three arrays, returns string

# Answer
> 2 votes
# Ruby, 128 bytes

```
->a,*l{t=a.sample;6.times{|i|puts"That's#{' not'if i<5} my #{t}#{i<5?', i':'! I'}ts %s is #{i<5?'to':?s}o %s."%l.map(&:sample)}}

```

Try it online!

# Answer
> 2 votes
# C#, ~~204~~ 203 bytes

```
()=>{int a(int x)=>new Random().Next(x);var j=t[a(5)];string s()=>$"That's not my {j}, its {p[a(25)]} is too {o[a(19)]}.\n";return s()+s()+s()+s()+s()+$"That's my {j}! Its {p[a(25)]} is so {o[a(19)]}.";};

```

It is my first answer on this site, so I hope it works well. It also needs those three things, but according to question those do not count:

```
   var t = new[] { "dinosaur", "lamb", "princess", "reindeer", "train" };
   var p = new[] {"back", "bells", "body", "bows", "crown", "dress", "ears",
          "engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
          "nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
          "tiara", "wheels", "windows" };
   var o = new[] {"bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
          "hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
          "soft", "sparkly", "squashy", "thick", "velvety", "woolly"};

```

Try it online!

One less byte thanks to Sok.

# Answer
> 1 votes
## Batch File, ~~434~~ 424 + 7 bytes

**Executed via `cmd/q/c`.**

*Code not counted*

```
set a=dinosaur lamb princess reindeer train
set b=back bells body bows crown dress ears engine fan flippers funnel hoobes horns neck nose roof sash side spines spots tail teeth tiara wheels windows
set c=bumpy fluffy furry fizzy glittery glossy hair red rough rusty shiny silky slippery soft sparkly squashy thick velvety woolly

```

*Code counted*

```
set q=random
set m=set/ar=1+%%%q%%%%%%%
call %m%5
for /f "tokens=%r%" %%x in ("%a%")do set x=%%x
:a
set/ad+=1
call %m%25
for /f "tokens=%r%" %%y in ("%b%")do set y=%%y
call %m%19
for /f "tokens=%r%" %%z in ("%c%")do echo That's not my %x%, its %y% is too %%z.
if %d% neq 5 goto a
call %m%25
for /f "tokens=%r%" %%y in ("%b%")do set y=%%y
call %m%19
for /f "tokens=%r%" %%z in ("%c%")do echo That's my %x%! Its %y% is so %%z.

```

I'll go through some challenges you must face and explain/justify what I did so others can improve.

**Choose a random element from an array**
I did this by generating a random number between `1` and `n` where `n` is the amount of elements in that array. I then used this random number as the token to grab in each `for` loop (`tokens=%r%`). Because I did it this way, I could not nest these `for` loops anymore, as `tokens=!r!` was not working for me (with delayed expansion). This would've saved quite a few bytes as it would've removed the need to save the tokens as variables (`set x=%%x`).

**Random number generation**
`m` is my random number generation macro. Doing it this way saves 32 bytes over doing it like `set/ar=%random%%%n+1` every line. You could semi-cheat and decide that tokens `y` and `z` are to be the same element:

```
call %m%19
for /f "tokens=%r%" %%y in ("%b%")do set y=%%y
for /f "tokens=%r%" %%z in ("%c%")do echo That's not my %x%, its %y% is too %%z.

```

This would, while still retaining some randomness, exclude the final 6 elements of `c`. This would save a minimum of 20 bytes, but I don't think this is true to the op's requirements.

**Theoretical Improvements**
I spent quite a while trying to make this "pseudo-code" work, while still saving bytes:

```
set 1-5=echo That's not my %x%, its %y% is too %%z.
set 6=echo That's my %x%! Its %y% is so %%z.
...
set/ad+=1
for /f "tokens=%r%" %%z in ("%c%")do call %%d%%

```

Unfortunately the setup for this is proving to take up way too many bytes to be profitable (have to implement in \< 144 bytes) but I can't shake the feeling that adding the last 4 lines of code are superfluous and janky.

# Answer
> 1 votes
# Pyth, ~~88~~ ~~78~~ 76 bytes

```
JONj_ms.ic"That's
 my

ts
 is
o
."b[?d" not"kJ?d", i""! I"OG?d\s"to"OH)6

```

Try it online!

The code presented above requires the following header:

```
=N["dinosaur""lamb""princess""reindeer""train")=G["back""bells""body""bows""crown""dress""ears""engine""fan""flippers""funnel""hooves""horns""neck""nose""roof""sash""side""spines""spots""tail""teeth""tiara""wheels""windows")=H["bumpy""fluffy""furry""fuzzy""glittery""glossy""hairy""red""rough""rusty""shiny""silky""slippery""soft""sparkly""squashy""thick""velvety""woolly")

```

There's a small issue with using the 'Header' feature in TIO with Pyth, as it looks like TIO joins the code blocks on newlines, and newlines are significant in Pyth. Here is a link to the same code using the 'Header' block, with a junk line in the output.

```
JONj_ms.ic"That's¶ my ¶¶ts ¶ is ¶o ¶."b[?d" not"kJ?d", i""! I"OG?d"to"\sOH)6   Newlines replaced with ¶
                                                                               Implicit: k="", b=newline
                                                                               From header: N=things, G=parts, H=properties
JON                                                                            Choose a random element from N, store in J
     m                                                                     6   Map [0-6), as d, using:
                                        ?d" not"k                                If d is truthy (i.e. not 0), yield " not", else ""
                                                 J                               J (the chosen thing)
                                                  ?d", i""! I"                   ", i" if d else "! I"
                                                              OG                 Random element from G
                                                                ?d"to"\s         "to" if d else "s"
                                                                        OH       Random element from H
                                       [                                  )      Wrap the previous 6 results in an array
         c"That's¶ my ¶¶ts ¶ is ¶o ¶."b                                          Split the template string on newlines
       .i                                                                        Interleave the template string elements with the previous list
      s                                                                          Concatenate
    _                                                                          Reverse lines
   j                                                                           Join on newlines, implicit print

```

*Edit: Rewrite to golf 10 bytes, previous version: `J+" my "ONV5%"That's not%s, its %s is too %s."[JOGOH;%"That's%s! Its %s is so %s."[JOGOH`*

# Answer
> 1 votes
# APL (Dyalog Unicode), 117 bytesSBCS

```
↑('That''s not my ',(t←T⊃⍨?5),', its ')∘,¨P[5?25],¨' is too '∘,¨V[5?19]
'That''s my ',t,'! Its',P[?25],'is so',V[?19]

```

Try it online!

`?N` generates a random index among the first N indices.

`M?N` generates M random indices (without replacement) among the first N indices.

`,` is concatenation

`t←T⊃⍨`… picks a random thing and calls it `t` for reuse in the last line.

`∘,¨` concatenates the string on the left to each string on the right.

concatenates each string on the left to each string on the right.

changes the list of strings into a character matrix so it prints right.

# Answer
> 1 votes
**JavaScript ES6, 149 (+15?) bytes**

```
a = ["dinosaur", "lamb", "princess", "reindeer", "train"]
b = ["back", "bells", "body", "bows", "crown", "dress", "ears",
  "engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
  "nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
  "tiara", "wheels", "windows"]
c = ["bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
  "hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
  "soft", "sparkly", "squashy", "thick", "velvety", "woolly"]

// r=x=>x[parseInt(Math.random()*x.length)] 164 for better random on fast pc

r=x=>x[new Date%x.length]
s=r(a)
g=j=>console.log(`That's ${j?`not my ${s}, its ${r(b)} is to`:`my ${s}! Its ${r(b)} is s`}o ${r(c)}.`)
a.map(g)
g()
```

# Answer
> 1 votes
# Perl 5.10, 127 bytes

Run with `perl -M5.010 -f filename.pl`.

```
my @t = qw(dinosaur lamb princess reindeer train);
my @r = qw(back bells body bows crown dress ears engine fan flippers funnel
           hooves horns neck nose roof sash side spines spots tail teeth tiara
           wheels windows);
my @p = qw(bumpy fluffy furry fuzzy glittery glossy hairy red rough rusty shiny
           silky slippery soft sparkly squashy thick velvety woolly);

sub r{rand@_}$a=" my $t[r@t]";say"That's not$a, its $r[r@r] is too $p[r@p]."for(1..5);say"That's$a! Its $r[r@r] is so $p[r@p]."

```

# Answer
> 1 votes
# ink, 119 bytes

```
~a=LIST_RANDOM(a)
-(l)That's{l<6: not} my {a}{l<6:, i|! I}ts {LIST_RANDOM(b)} is {l<6:to|s}o {LIST_RANDOM(c)}
{l<6:->l}

```

With the lists defined as

```
LIST a=(dinosaur),(lamb),(princess),(reindeer),(train)
LIST b=(back),(bells),(body),(bows),(crown),(dress),(ears),(engine),(fan),(flippers),(funnel),(hooves),(horns),(neck),(nose),(roof),(sash),(side),(spines),(spots),(tail),(teeth),(tiara),(wheels),(windows)
LIST c=(bumpy),(fluffy),(furry),(fuzzy),(glittery),(glossy),(hairy),(red),(rough),(rusty),(shiny),(silky),(slippery),(soft),(sparkly),(squashy),(thick),(velvety),(woolly)

```

Try it online!

---

Though depending on what counts as a list, there are other approaches. If a list can be a function that randomly returns a list item, the following approach is only 91 bytes:

```
~temp t=u()
-(l)That's{l<6: not} my {t}{l<6:, i|! I}ts {p()} is {l<6:to|s}o {q()}
{l<6:->l}

```

(with the "lists" defined as follows)

```
==function u
~return "{~dinosaur|lamb|princess|reindeer|train}"
==function p
~return "{~back|bells|body|bows|crown|dress|ears|engine|fan|flippers|funnel|hooves|horns|neck|nose|roof|sash|side|spines|spots|tail|teeth|tiara|wheels|windows}"
==function q
~return " {~bumpy|fluffy|furry|fuzzy|glittery|glossy|hairy|red|rough|rusty|shiny|silky|slippery|soft|sparkly|squashy|thick|velvety|woolly}."

```

Try it online!

---

There's also the following approach.

```
~temp t="{~dinosaur|lamb|princess|reindeer|train}"
-(l)That's{l<6: not} my {t}{l<6:, i|! I}ts {~back|bells|body|bows|crown|dress|ears|engine|fan|flippers|funnel|hooves|horns|neck|nose|roof|sash|side|spines|spots|tail|teeth|tiara|wheels|windows} is {l<6:to|s}o {~bumpy|fluffy|furry|fuzzy|glittery|glossy|hairy|red|rough|rusty|shiny|silky|slippery|soft|sparkly|squashy|thick|velvety|woolly}
{l<6:->l}

```

Try it online!

This solution is 389 bytes, but if the shuffle literals (which in this scenario can't really be moved) count as list definitions and can be excluded from the byte count, this drops to 80 bytes.

# Answer
> 0 votes
# Bash +awk, 209 bytes

```
T=$(shuf $1|head -1)
join <(sed "s/.*/$T\t&/" $2) <(sed "s/.*/$T\t&/" $3)|shuf|awk 'NR<6{printf "That'\''s not my %s, its %s is too %s.\n",$1,$2,$3}NR==6{printf "That'\''s my %s! Its %s is so %s.\n",$1,$2,$3}'

```

Try it online!

Accepts inputs as `things parts properties` where each is a file with one item per line of the desired type.

This is a file-centered approach. May try an array-centered approach later to see if it can be improved.

# Answer
> -2 votes
# Python 3, 130 bytes

Taking your requirements literally, and taking carriage returns to be one byte each:

```
y=0
def x():
    global y
    y=1-y
    print(("That's not my lamb, it's "+b[0:1][y]+" is too red\n")*5+"That's my lamb! Its fan is so red")

```

---
Tags: code-golf
---


# Question
Title: Count rotary dial pulses in a phone number (including letters)
In your grandparents' day, dialing a phone number was done with a rotary dial like this:

To dial each digit, put your finger in the corresponding hole, pull it over to the finger stop, and release it. A mechanism will cause the dial to spin back to its resting position, and the phone will disconnect and reconnect a circuit a specified number of times, making audible clicks.

Dialing the digit *N* requires *N* such “pulses”, except for N=0 which is ten pulses.

Rotary phones have the property that large digits (8, 9, 0) take longer to dial than small digits (1, 2, 3). This was an important consideration in drawing up early area code maps, and why New York City with its heavy population (and phone line) density got 212 (only 5 pulses), while while 907 (26 pulses) went to sparsely-inhabited Alaska. Of course, this all became irrelevant when touch-tone dialing became popular.

# The challenge

Write, in as few bytes as possible, a program or function that takes as input a string (or sequence of characters) containing a telephone number, and outputs its number of rotary dial pulses. These are to be counted as follows:

## Digits

* Digits 1-9 count as that number of pulses.
* Digit 0 counts as 10 pulses.

## Letters

Note that digits 2-9 on the dial have letters of the Latin alphabet associated with them. These were originally intended for named exchanges, but were latter re-appropriated for phonewords, and for text message input systems.

You must support having letters in your phone numbers, using the E.161 assignment of letters to digits:

* A, B, C = 2
* D, E, F = 3
* G, H, I = 4
* J, K, L = 5
* M, N, O = 6
* P, Q, R, S = 7
* T, U, V = 8
* W, X, Y, Z = 9

You may assume that the input has already been case-folded, to either upper or lower case.

## Other characters

You **must** allow arbitrary use of the characters `()+-./` and space as formatting separators. You **may** chose to allow *any* non-alphanumeric character for this purpose, if it's easier to implement.

These characters do not contribute to the pulse count.

# Example code

A non-golfed lookup table and function in Python:

```
PULSES = {
    '1': 1,
    '2': 2, 'A': 2, 'B': 2, 'C': 2,
    '3': 3, 'D': 3, 'E': 3, 'F': 3,
    '4': 4, 'G': 4, 'H': 4, 'I': 4,
    '5': 5, 'J': 5, 'K': 5, 'L': 5,
    '6': 6, 'M': 6, 'N': 6, 'O': 6,
    '7': 7, 'P': 7, 'Q': 7, 'R': 7, 'S': 7,
    '8': 8, 'T': 8, 'U': 8, 'V': 8,
    '9': 9, 'W': 9, 'X': 9, 'Y': 9, 'Z': 9,
    '0': 10
}

def pulse_count(phone_num):
    return sum(PULSES.get(digit, 0) for digit in phone_num)

```

# Example input and output

* `911` → 11
* `867-5309` → 48
* `713 555 0123` → 42
* `+1 (212) PE6-5000` → 57
* `1-800-FLOWERS` → 69
* `PUZZLES` → 48

# Answer
> 28 votes
# 05AB1E, ~~19~~ ~~18~~ ~~17~~ 15 bytes

```
AÁ0ªā6+žq÷9š‡þO

```

Try it online!

This is the first answer to use π. Why use π, you might ask? Well, the letters are associated with 22233344455566677778889999, in order. Notice how most digits repeat 3 times, but 7 repeats 4 times. You could say that each digit repeats (3+1/7) times, on average. I wonder if there’s any number that’s approximately 3+1/7 and takes fewer bytes than 22/7…

This only gives 4 7s, not 4 9s, so we still need to handle Z as a special case.

```
A               # alphabet (abcdefghijklmnopqrstuvwxyz)
 Á              # rotate right (zabcdefghijklmnopqrstuvwxy)
  0ª            # append 0 (zabcdefghijklmnopqrstuvwxy0)

ā6+             # range [7..33]
   žq÷          # divide by π (22233344455566677778889991010)
      9š        # prepend 9 (922233344455566677778889991010)

‡               # transliterate the implicit input with the two lists above
                # this replaces z → 9, a → 2, … y → 9, 0 → 10
 þ              # remove all non-digits
  O             # sum

```

# Answer
> 9 votes
# C# (Visual C# Interactive Compiler), 51 bytes

```
n=>n.Sum(x=>x>64?(x-59-x/83-x/90)/3:x>47?1-~x%~9:0)

```

Saved 1 byte thanks to @recursive

Saved 10 bytes thanks to @ExpiredData's observation that only `() +-/.` will be in the input

Try it online!

```
n =>                     // Function taking input as string
  n.Sum(x =>             // Map each value 'x' through the following
    x>64 ?               //   If 'x' is an uppercase letter
      (x-59-x/83-x/90)/3 //     Take each char's ASCII value subtracted by 59, and subtract
                         //     one if the char is 'S' and one if the char is 'Z'
    : x>47 ?             //   Else if the char is a digit
      1-~x%~9            //   Take 1 - (-x - 1) % -10 (Maps 0 to 10, and 1-9 to themselves
    : 0                  //   Else, 0
  )                      // And sum it all up, then return it

```

# Answer
> 5 votes
# Python 2, 74 bytes

```
lambda s:sum([(n-59-n/83-n/90)/3,1-~n%~9][n<58]for n in map(ord,s)if n>47)

```

Try it online!

Does some arithmetic on the ASCII value for each character. The first option checks for letters and the second options checks for numbers. The clarification that all punctuation characters allowed in the input are ones with ASCII values less than 48 let me simplify the logic, but a new method altogether might now be better.

# Python 2, 84 bytes

```
lambda s:sum(1+'1xxxx2ABCx3DEFx4GHIx5JKLx6MNOx7PQRS8TUVx9WXYZ0'.find(c)/5for c in s)

```

Try it online!

Uses a hardcoded lookup string, with each block of 5 characters corresponding to the characters giving each value starting with 1. Blank spaces are filled with `x`, which can't be in the input which is capitalized. Fortuitously, characters not appearing in the string produce `-1` for the `.find` which gives a summand of zero.

# Answer
> 5 votes
# JavaScript (Node.js), ... ~~76~~ 69 bytes

```
s=>s.replace(/\w/g,q=>w+=1/q?+q||10:parseInt(q,35)*.32-1|0||9,w=0)&&w

```

Try it online!

-7 thanks @Arnauld!

### Explanation

```
 q |     1/q     |  +q  | parseInt(q,35)*.32 | parseInt(q,35)*.32-1|0 | Output
---+-------------+------+--------------------+------------------------+--------
 0 | Infinity(T) | 0(F) |         N/A        |           N/A          |   10
 1 |  1.0000(T)  | 1(T) |         N/A        |           N/A          |    1
 2 |  0.5000(T)  | 2(T) |         N/A        |           N/A          |    2
 3 |  0.3333(T)  | 3(T) |         N/A        |           N/A          |    3
 4 |  0.2500(T)  | 4(T) |         N/A        |           N/A          |    4
 5 |  0.2000(T)  | 5(T) |         N/A        |           N/A          |    5
 6 |  0.1666(T)  | 6(T) |         N/A        |           N/A          |    6
 7 |  0.1428(T)  | 7(T) |         N/A        |           N/A          |    7
 8 |  0.1250(T)  | 8(T) |         N/A        |           N/A          |    8
 9 |  0.1111(T)  | 9(T) |         N/A        |           N/A          |    9
 A |    NaN(F)   |  N/A |        3.20        |          2(T)          |    2
 B |    NaN(F)   |  N/A |        3.52        |          2(T)          |    2
 C |    NaN(F)   |  N/A |        3.84        |          2(T)          |    2
 D |    NaN(F)   |  N/A |        4.16        |          3(T)          |    3
 E |    NaN(F)   |  N/A |        4.48        |          3(T)          |    3
 F |    NaN(F)   |  N/A |        4.80        |          3(T)          |    3
 G |    NaN(F)   |  N/A |        5.12        |          4(T)          |    4
 H |    NaN(F)   |  N/A |        5.44        |          4(T)          |    4
 I |    NaN(F)   |  N/A |        5.76        |          4(T)          |    4
 J |    NaN(F)   |  N/A |        6.08        |          5(T)          |    5
 K |    NaN(F)   |  N/A |        6.40        |          5(T)          |    5
 L |    NaN(F)   |  N/A |        6.72        |          5(T)          |    5
 M |    NaN(F)   |  N/A |        7.04        |          6(T)          |    6
 N |    NaN(F)   |  N/A |        7.36        |          6(T)          |    6
 O |    NaN(F)   |  N/A |        7.68        |          6(T)          |    6
 P |    NaN(F)   |  N/A |        8.00        |          7(T)          |    7
 Q |    NaN(F)   |  N/A |        8.32        |          7(T)          |    7
 R |    NaN(F)   |  N/A |        8.64        |          7(T)          |    7
 S |    NaN(F)   |  N/A |        8.96        |          7(T)          |    7
 T |    NaN(F)   |  N/A |        9.28        |          8(T)          |    8
 U |    NaN(F)   |  N/A |        9.60        |          8(T)          |    8
 V |    NaN(F)   |  N/A |        9.92        |          8(T)          |    8
 W |    NaN(F)   |  N/A |       10.24        |          9(T)          |    9
 X |    NaN(F)   |  N/A |       10.56        |          9(T)          |    9
 Y |    NaN(F)   |  N/A |       10.88        |          9(T)          |    9
 Z |    NaN(F)   |  N/A |         NaN        |          0(F)          |    9

```

All of `[space]().+-/` are not captured by `/\w/g`, so they won't affect the total.

# Answer
> 5 votes
# Perl 5 `-p`, ~~52~~ 51 bytes

*@Grimy gets credit for -1*

```
y/A-Z/22233344455566677778889/;map$\+=$_||10,/./g}{

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Unicode), 27 bytesSBCS

Anonymous tacit prefix function.

```
+/'@ADGJMPTW'∘⍸+11|(1⌽⎕D)∘⍳

```

Try it online!

`(``)∘⍳` find the **ɩ**ndex\* of each character in the following string:
* elements that are not found, get the index 1+the maximum index, i.e. 11
`⎕D` the digits: `"0123456789"`

`1⌽` cyclically rotate one step left; `"1234567890"`

`11|` division remainder when divided by 11\*
* this gives 0 for all non-digits
`+` add that to the following:

`'@ADGJMPTW'∘⍸` the **ɩ**nterval **ɩ**ndex\* for each character
* So \[−∞,"@") gives 0, \["@","A") gives 1, \["A","D") gives 2, etc.
`+/` sum that

# Answer
> 4 votes
# , 39 bytes

```
1#.'?@CFILOSVZ'&I.+11|1+'1234567890'i.]

```

Try it online!

A port of Adám's APL solution

# Answer
> 4 votes
# Retina 0.8.2, 34 bytes

```
T`WTPMJGDA`Rd
}T`L`2L
0
55
\d
$*
1

```

Try it online! Link includes test cases. Explanation:

```
T`WTPMJGDA`Rd

```

Convert the letters `WTPMJGDA` to the digits `9..0`.

```
}T`L`2L

```

Shuffle all the remaining letters down by 1 and repeat until all of the letters have been converted to digits.

```
0
55

```

Replace `0` with `55` as they take the same number of pulses to dial.

```
\d
$*
1

```

Take the digital sum.

# Answer
> 3 votes
# C (gcc), 94 89 86 80 bytes

Thanks to ceilingcat, nwellnhof and Rogem for the suggestions.

```
c;f(char*s){c=*s-48;s=*s?(c<10U?c?c:10:c-17<26U?(c-11-c/35-c/42)/3:0)+f(s+1):0;}

```

Try it online!

# Answer
> 3 votes
# K4, 44 bytes

**Solution:**

```
+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?

```

**Examples:**

```
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"911"
11
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"867-5309"
48
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"+1 (212) PE6-5000"
57
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"1-800-FLOWERS"
69

```

**Explanation:**

Naive approach, likely pretty golfable. Lookup index of character, lookup score, sum.

```
+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")? / the solution
                                           ? / lookup
                          (               )  / do this together
                                       "0"   / string "0"
                                      ,      / join with
                                  .Q.n       / string "0123456789"
                                1_           / drop first
                               ,             / join with
                           .Q.A              / "A..Z"
  (                      )                   / do this together
                      !10                    / range 0..9
                     ,                       / join with
     (              )                        / do this together
               4 3 4                         / list (4;3;4)
              ,                              / join with
         (5#3)                               / list (3;3;3;3;3)
        &                                    / where, creates list 0 0 0 1 1 1 2 2 etc
      1+                                     / add 1
   1+                                        / add 1
+/                                           / sum up

```

# Answer
> 3 votes
# Perl 6, 53 bytes

```
{sum +<<m:g/\d/X||10}o{S:g[<:L>]=$/.ord*.313-28+|0+9}

```

Try it online!

Multiplies the ASCII code with 0.313 instead of 1/3 and uses bitwise OR which rounds to zero to get the correct bias.

# Answer
> 2 votes
# Jelly, ~~33~~ 24 bytes

```
7r32:ØP«9Ṿ€ØAżFyfØDV€o⁵S

```

Try it online!

A monadic link taking a string as its argument and returning the number of pulses. Rewritten inspired by @Grimy’s 05AB1E answer so be sure to upvote them!

# Answer
> 2 votes
# Bash, 256 bytes

You can replace the `(( … ))` constructs with `let` for identical byte count. There may be a good algorithm to reduce the case statements but not found it so far. With a bit of rework you could make it a function also (but not in same or less bytes unless you can discount the `function fname { … }` top and tail).

```
read p;while ((${#p}>0));do case ${p:0:1} in ([1-9]) ((d+=${p:0:1}));; ([0]) ((d+=10));; ([ABC) ((d+=2));; ([P-S]) ((d+=7));; ([W-Z]) ((d+=9));;([DEF]) ((d+=3));; ([GHI]) ((d+=4));; ([JKL]) ((d+=5));; ([MNO]) ((d+=6));; (?) d=$d; esac;p=${p#?};done;echo $d

```

Try it online!

A better solution using the map character technique makes use of the `tr` tool:

# \[Bash with tr\], 173 bytes

```
read p;p=$(echo $p|tr A-Z 22233344455566677778889999);while ((${#p}>0));do case ${p:0:1} in ([1-9]) ((d+=${p:0:1}));; ([0]) ((d+=10));; (?) d=$d; esac;p=${p#?}; done;echo $d

```

Try it online!

# Answer
> 2 votes
# PowerShell,109 102 87 bytes

```
$(switch -r($args|% t*y){\d{$_}[A-Y]{("{0}"-f(.313*$_-18))[0]}[Z]{9}0{10}})-join'+'|iex

```

Try it online!

EDIT: Used @mazzy's idea for a regex switch with some string formatting to cast char -\> int -\> string and grab only the first 'digit'

**Original:**

```
[char[]]"$args"|%{$a+=(48,(('22233344455566677778889999')[$_-65],(58,$_)[$_-ne48])[$_-lt64])[$_-gt47]-=48};$a

```

I was hoping to get \<100 bytes, so I'll keep looking at it to see if there is anything else I can do. There's probably a way to remove the number string

Sorry if this is confusing as I nested arrays with boolean indexing statements but -

**Explanation:**

`[char[]]"$args"|%{` reads the input casted as a string and then explodes it to a char array and begins a for-each loop with checking `()[$_-gt47]` to see if any `()+-./` was entered (all have ascii character values \<48)
Note: Powershell accepts `$true` and `$false` as `1` and `0` respectively for array indices

Then we get either `48` for the symbols, or:
`('22233344455566677778889999'[$_-65],(58,$_)[$_-ne48])[$_-lt64]`

The `[$_-lt64]` checks for a number or a letter (all assumed capital here). If it's a letter, `'22233344455566677778889999'[$_-65]` changes it to 0-25 to index into the array and output the pulse value (as a char). If the character is a number, we instead look at: `(58,$_)[$_-ne48]` checking for `0` and outputting `58` or just the numeric char itself.

Around everything `$a+= ... -=48` initializes a numeric variable $a at `0` and then adds the output. The output is the ascii char value of a number, so subtract `48`.

Note: if the input was a symbol, we get `$a+=48-48`, effectively ignoring it. If it was `0`, we get `$a+=58-48` to obtain our +10

Lastly, `;$a` just outputs our final value post for-each loop

# Answer
> 2 votes
# PowerShell, ~~95~~ ~~85~~ 79 bytes

*inspired by nwellnhof's answer.*

*inspired by `[0]` from Sinusoid's answer.*

```
$(switch -r($args|% t*y){\d{$_}0{10}[A-Y]{"$(.313*$_-18)"[0]}Z{9}})-join'+'|iex

```

Try it online!

Unrolled version:

```
$(
    switch -r($args|% toCharArray){
        \d    {$_}
        0     {10}
        [A-Y] {"$(.313*$_-18)"[0]}
        Z     {9}
    }
)-join '+'|Invoke-Expression

```

```
key .313*$_-18 "$(...)"[0]
--- ---------- -----------
  A      2.345 2
  B      2.658 2
  C      2.971 2
  D      3.284 3
  E      3.597 3
  F      3.910 3
  G      4.223 4
  H      4.536 4
  I      4.849 4
  J      5.162 5
  K      5.475 5
  L      5.788 5
  M      6.101 6
  N      6.414 6
  O      6.727 6
  P      7.040 7
  Q      7.353 7
  R      7.666 7
  S      7.979 7
  T      8.292 8
  U      8.605 8
  V      8.918 8
  W      9.231 9
  X      9.544 9
  Y      9.857 9

```

# Answer
> 1 votes
# Stax, 21 bytes

```
éT6T&\²|└t5φ╛│█♪√┘↑▓^

```

Run and debug it

# Answer
> 1 votes
# Kotlin, 113 bytes

```
{s:String->var t=0
for(c in s){val v=c-'0'
t+=when(v){0->10
in 1..9->v
in 17..42->(v-11-v/35-v/42)/3
else->0}}
t}

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~134~~ 123 bytes

```
f=lambda n:sum(map(int,n.translate(n.maketrans('ADGJMPTWBEHKNQUXCFILORVYSZ','23456789'*3+'79','()+-./ '))))+10*n.count('0')

```

Try it online!

-11 bytes thanks to @dan04

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


title: Pandemic Outbreak Calculator

text:
# Question
Title: Pandemic Outbreak Calculator
In the board game Pandemic, an **outbreak** occurs when a city contains more than 3 disease cubes. When the outbreak occurs, any disease cubes in the city in excess of 3 are removed, and each city connected to it gains one disease cube. This means that chain reactions can, and will occur.

**Important note: Each city may only outbreak once in each chain reaction.**

## Input

A list of cities each containing:

* An integer representing the number of disease cubes .
* And a number of identifiers of the form (A, B ... AA, AB) (lowercase is allowed) representing which cites in list order it is connected to.

## Output

A list of integers representing the number of disease cubes in each city after outbreaks have been resolved.

## Winning Condition

This is , so the shortest code in bytes wins.

# Answer
> 3 votes
# Python 3, 201 bytes

```
f=lambda d,e,v=[],n=enumerate:any((D>3)>(i in v)for i,D in n(d))and f([(i in v)and D or(min(3,D)+sum((k not in v)*(d[k]>3)for k in E))for i,(D,E) in n(zip(d,e))],e,v+[i for i,D in n(d)if D>3])or sum(d)

```

Try it online!

Worst case O(n) on the number of cities. `d` is a list of disease counts, `e` is a list of city connections by `0`-indexed position corresponding to `d`, and `v` is the visited array (which should not be given as input, obviously).

For the case `[4, 3, 2]` with connections `0 <-> 1`, `1 <-> 2`, and `0 <-> 2`, first, city `0` outbreaks and becomes `3` and sets city `1` to `4` and city `2` to `3`. Then, city `1` outbreaks and becomes `3` and sets city `2` to `4` (city `0` already had an outbreak). Finally, city `2` has an outbreak and nothing can be affected, leaving all three cities on `3` disease cubes, totalling `9`.

---
Tags: code-golf, graph-theory, board-game
---


title: The year counter is here

text:
# Question
Title: The year counter is here
Create a program that, given an integer N, outputs the number of years we have to get to N A.D. or how many years it has been since N A.D, as a string or int. For example, given 2014, the program should output 5 as it has been that many years since 2014. Input of the year in which you run the program should result in 0.

Treat the input "0" however you like: as its own year, as 1 A.D. or as 1 B.C. This means that you can pretend there IS a year zero and have all BC years be off by one.

Negative integers (integers with - in front of them) are treated as years B.C. For example inputting -2 would result in the program telling how many years it has been since 2 B.C.

Treat improper inputs (inputs that don't only use numbers and the dash as characters (abcd), or use the dash by itself or use it wrongly (e.g. 6-)) however you want, error or exit or something else.

The winning program is the program with the shortest code that does all of this. Have fun.

# Answer
# 05AB1E, 3 bytes

```
žgα

```

Try it online!

**Explanation**

```
  α   # absolute difference between
      # implicit input
žg    # and current year

```
> 2 votes

# Answer
# Java 8, 46 bytes

```
n->(n-=java.time.Year.now().getValue())<0?-n:n

```

Try it online.

Or alternatively:

```
n->Math.abs(n-java.time.Year.now().getValue())

```

Try it online.
> 2 votes

# Answer
# Japt, 3 bytes

```
aKi

```

Try it

```
aKi     :Implicit input of year
a       :Absolute difference with
 K      :  Date
  i     :  Get year

```
> 1 votes

# Answer
# Pyth, 4 bytes

```
a.d3

```

Try it online!

**Explanation:**

```
a.d3Q - full program. implicit Q added.
a     - absolute difference of
 .d3  - current year and
    Q - implicit input

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler) with `/u:System.Math` and `/u:System.DateTime` flags, ~~32~~ 18 bytes

```
n=>Abs(Now.Year-n)

```

Try it online.
> 1 votes

# Answer
# PHP, 22 bytes

```
<?=date('Y')-$argv[1];

```

Try it online!
> 0 votes

# Answer
# Python 3, 66 bytes

```
from datetime import*
print(abs(int(input())-datetime.now().year))

```

Try it online!

Gives 5 for 2014 because it's 2019, not 2018.
> 0 votes

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

```
a=>Math.abs(Date().split` `[3]-a)

```

Try it online!

-6 bytes thanks to Luis felipe De jesus Munoz
> 0 votes

# Answer
# Red, 30 bytes

```
func[y][absolute y - now/year]

```

Try it online!
> 0 votes

# Answer
# C++ (gcc), ~~131~~ 127 bytes

```
#include<ctime>
#include<cstdio>
int main(){long y,t=time(0);scanf("%d",&y);y-=gmtime(&t)->tm_year+1900;printf("%d",y<0?-y:y);}

```

Try it online!
> 0 votes

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


title: The ASCII Architect

text:
# Question
Title: The ASCII Architect
You don't want to pay money for the expensive architectural program, so you decide to roll your own. You decide to use ASCII to design your buildings. Your program will take in a single string formatted in a specific way, and the program will output the building.

## Input

Input consists of a single line of characters. It can be assumed to only contain the letters `a-j`, the numbers `1-9`, and the symbols `-` and `+`.

## Output Description

For each letter `a-j`, the program will output a vertical line as follows. We will call this a column.

```
         .
        ..
       ...
      ****
     *****
    ******
   -------
  --------
 +++++++++
++++++++++
abcdefghij

```

For instance, the input `abcdefgfedefghgfedc` would output:

```
             .
      *     ***
     ***   *****
    ***** *******
   ---------------
  -----------------
 ++++++++++++++++++
+++++++++++++++++++

```

A letter may be prefixed with a positive integer `n`, which will add `n` whitespace characters below the column. We will call this an offset. For instance, using `S` to notate a whitespace, the input `3b2b3b` would output:

```
+ +
+++
S+S
SSS
SSS

```

A letter may also be prefixed with a *negative* integer `-m`, which will *remove* the bottom `m` *non-whitespace* characters of the column (not replace them with whitespace, remove them entirely). We will call this a slice. For instance, the input `-1j-2j-3j-4j-5j-6j-7j-8j` would output:

```
.
..
...
*...
**...
***...
-***...
--***...
+--***..

```

An offset and a slice can be applied to the same line, but the offset must go first. In other words, the letter may be prefixed with `n-m`, where `n` is the size of the offset, and `m` is the size of the slice. For instance, using `S` to notate a whitespace, the input '2-4j' would output:

```
.
.
.
*
*
*
S
S

```

Lastly, the `+` operator used between two columns indicates that they should be stacked on top of each other in the same column instead of in seperate columns. For instance, the input \`2-4ja' outputs:

```
.
.
.
*
*
*
S
S+

```

Whereas the input `2-4j+a` outputs:

```
+
.
.
.
*
*
*
S
S

```

Here is a sample input:

```
abiehef+ehfhabc

```

And the resultant output:

```
      *
      -
  .   -
  . . +. .
  * * +* *
  * * ****
  ********
  --------
  --------  -
 +++++++++ ++
+++++++++++++

```

Looks like an old destroyed castle tower of some sort.

Here is another sample input:

```
6b5b+a6b1-2d+3-4f1-2d+-2c+2-4f+1-2d+-2c2-2d+1-4g+1-2c+b+-2c+-4e2-7j+-4g+d+-2c+-4f2-7j+-5h+b+-2c+a+-3f2-7j+-7i+-4e+b+b+a+-4f2-7i+a+-7h+-4f+b+b+a+-4f2-7j+-7h+-4f+a+-7h+a+-7i+-4f2-7j+-7i+-6h+a+-7i+b+-4e3-7i+a+-7h+-4e+a+-7h+b+1-7h3-7j+1-4f+-7h+b+-4f+a3-7j+2-4f+a+-4f+b3-2d+-2d+3-4g+b3-2d+-2d+-2c

```

And the resultant output:

```
      ****** +++
     ******+.*++
     ---++.+ ***
    -+-+++..++**
    -+--+++.+++*
    --++++.+..*
      +++++.+**
+++****.******  -
+++*****.**..  --
 +   ***....+..--
      ...+.....--
    --.........--
   ---......
   --

```

(It was supposed to be Mario but didn't turn out very good...)

If the specification still isn't clear, I have a non-golfed implementation written in Python 2.7. You can run it and experiment to get a feel for how the specification works. You may also choose to laugh at my programming skills.

This is code-golf, so shortest entry wins. Ask questions in comments if unclear.

# Answer
## Ruby, ~~223~~ 214 bytes

```
g=$*[0].split(/(?<=[a-j])(?!\+)/).map{|r|r.scan(/(\d*)(-\d+)?([a-j])/).map{|a,b,c|' '*a.to_i+'++--***...'[-b.to_i..c.ord-97]}*''}
puts g.map{|s|s.ljust(g.map(&:size).max).chars.reverse}.transpose.map(&:join).join$/

```

That was fun. :)

Although it should be quite obvious, I discovered a new way to do these challenges where strings have be constructed from columns: just do them in rows, and transpose the array of characters before joining everything.

```
g=$*[0].split(/(?<=[a-j])(?!\+)/)               # Split into columns.
       .map{|r|                                 # For each column
            r.scan(/(\d*)(-\d+)?([a-j])/)       # Split into components.
             .map{|a,b,c|                       # For each component
                ' '*a.to_i+                     # Prepend spaces if any.
                '++--***...'[-b.to_i..c.ord-97] # Select the appropriate slice of the tower.
            }*''                                # Join all components together.
        }
puts g.map{|s|                                  # For each column
            s.ljust(g.map(&:size).max)          # Pad with spaces on the right such that.
                                                # all columns are the same height.
            .chars.reverse                      # Turn into character array and reverse.
      }
      .transpose                                # Mirror in the main diagonal.
      .map(&:join)                              # Join lines.
      .join$/                                   # Join columns.

```
> 10 votes

# Answer
# Cobra - 473

I don't think Cobra's ever going to win one of these :/

```
use System.Text.RegularExpressions
class P
    def main
        r=Regex.matches(Console.readLine,r'(?<=^|[a-j])(([^a-j]*[a-j])+?)(?=[^+]|$)')
        z,l=0String[](r.count)
        for m in r.count,for n in'[r[m]]'.split('+'),l[m]+=' '.repeat(int.parse('0[Regex.match(n,r'(?<!-)\d+')]'))+'++--***...'[int.parse('0[Regex.match(n,r'(?<=-)\d+')]'):' abcdefghij'.indexOf(n[-1:])]
        for y in l,if y.length>z,z=y.length
        for x in-z+1:1
            for y in l,Console.write(if(-x<y.length,y[-x],' '))
            print

```

All nice and commented:

EDIT: Just realized this looks suspiciously similar to the Ruby solution. Great minds think alike?

```
use System.Text.RegularExpressions
class P
    def main
        r=Regex.matches(Console.readLine,r'(?<=^|[a-j])(([^a-j]*[a-j])+?)(?=[^+]|$)')
        # Split into columns
        z,l=0,String[](r.count)
        # Assign the column-array
        for m in r.count
        # Loop through columns
            for n in'[r[m]]'.split('+')
            # Loop through individual letter instructions
            # - within columns
                l[m]+=
                # Add characters to the last column
                    ' '.repeat(int.parse('0[Regex.match(n,r'(?<!-)\d+')]'))+
                    # Any spaces, plus
                    '++--***...'[:' abcdefghij'.indexOf(n[-1:])]
                    # The default column string
                        [int.parse('0[Regex.match(n,r'(?<=-)\d+')]'):]
                        # Sliced to the right length
        for y in l,if y.length>z,z=y.length
        # Determine the maximum length of any column
        for x in-z+1:1
            for y in l
            # Loop through columns so that they rotate to the left
                Console.write(if(-x<y.length,y[-x],' '))
                # Write the character in the current position
            print
            # Insert newlines

```
> 2 votes

# Answer
# Lua - 451

```
a=arg[1]j='++--***...'I=io.write M=string.match U=string.sub T=table.insert n=''y=0 t={}m=0 for i in a:gmatch('[%-%d]*[a-j]%+?')do b=M(i,'-(%d)')b=b or 0 s=M(U(i,1,1),'%d')s=s or 0 n=n..(' '):rep(s)..U(U(j,1,M(U(i,-2),'[a-j]'):byte()-96),1+b,-1)if U(i,-1,-1)~="+"then T(t,n)m=m<#n and #n or m n=""y=y+1 end end T(t,n)n=''for k,v in pairs(t)do n=#v<m and n..v..(' '):rep(m-#v)or n..v end for i=m,1,-1 do for k=0,m*y-1,m do I(U(n,i+k,i+k))end I'\n'end

```

Nothing special. It was fun to rename a butt-load of functions for once though. I'll edit the ungolfed code in later.

Try it out here. Sample Output:
> 2 votes

# Answer
# PowerShell, ~~214~~ ~~212~~ ~~209~~ ~~206~~ 200 bytes

*-3 bytes thanks @Veskah*

```
switch -r($args-split'(-?.)'){\+{$c=1}\d{sv('ps'[0-gt$_])$_}[a-j]{if(!$c){$t+=,''}$t[-1]+=' '*$p+-join'++--***...'[-$s..($_[0]-97)];$c=$p=$s=0}}($t|% Le*|sort)[-1]..1|%{-join($t|% *ht $_|% ch*($_-1))}

```

Try it online!

Less golfed version:

```
# make table with lines instead columns
switch -r($args-split'(-?.)'){
    \+ {$c=1}
    \d {set-variable ('ps'[0-gt$_]) $_}
    [a-j] {
        if(!$c){$t+=,''}
        $t[-1]+=' '*$p+-join'++--***...'[-$s..($_[0]-97)]
        $c=$p=$s=0
    }
}
# transpose
($t|% Length|sort)[-1]..1|%{
    -join($t|% padRight $_|% chars($_-1))
}

```
> 1 votes

# Answer
# Python 3, 268 bytes

```
import re
q,t=[(p,' '*int(o or 0)+'++--***...'[-int(s or 0):ord(l)-96])for p,o,s,l in re.findall('(\+?)(\d?)(-\d)?(.)',input())],[]
while q:p,s=q.pop(0);t+=[t.pop()+s if p else s]
t=[*zip(*[[*c.ljust(max(map(len,t)))]for c in t])][::-1]
for l in t:print(*l,sep='')

```

Mostly ungolfed:

```
# import the regex module
import re

# array to store initial input
q = []
# array to store translated output
t = []

# split string from stdin into column groups, like: ('plus or blank', 'offset or blank', 'slice or blank', 'letter')
# ex: 6b1-2d+a would become:
# [('','6','','b'), ('', '1', '-2', 'd'), ('+', '', '', 'a')]
i = re.findall('(\+?)(\d?)(-\d)?(.)',input())

# iterate through the groups returned by the regex
for p,o,s,l in i:
    # create offset string
    # int() cannot parse '', but empty strings are falsey,
    # so (o or 0) is equivalent to 'parse the string as an int, or return 0 if it is empty'
    offset = ' ' * int(o or 0)

    # get the starting point of the slice
    # since the regex returns the minus, it must be negated after converting the string to an int
    # as before, (s or 0) ensures that the slice is converted to an int properly
    start = -int(s or 0)
    # since 'a' is ordinal 97, this ensures that the end position will be 1-9
    end = ord(l) - 96
    # slice the largest possible column string with the calculated start and end positions
    a = '++--***...'[start:end]
    # add the space offset
    a = offset + a
    # add the plus sting and the column string to the array
    q.append( (p, a) )

# while q is not empty
while q:
    # remove the first item from the list and separate it into a plus variable and a column string
    p, s = q.pop(0)

    # if p is not blank, it is a '+'
    # if p is truthy, remove the last item added and add s to it
    # otherwise just return s
    # append the resulting item to the ongoing list
    t += [t.pop()+s if p else s]

temp = []
for c in t:
    # call len() on all items in t, then return the maximum length
    m = max(map(len, t))
    # left justify c by adding spaces to the right, up to m total characters
    c = c.ljust(m)
    # unpack c into a list
    # this is equivalent to list(c), but shorter
    c = [*c]
    # add the list of characters to the array
    temp.append(c)

t = temp

# t is currently a list of rows, and needs to be rotated so that it displays correctly
# input: 'abcdefghij'
# before:
#
# +
# ++
# ++-
# ++--
# ++--*
# ++--**
# ++--***
# ++--***.
# ++--***..
# ++--***...
#
# after:
#
#  ++++++++++
#   +++++++++
#    --------
#     -------
#      ******
#       *****
#        ****
#         ...
#          ..
#           .
#
t = [*zip(*t)]
# t is currently upside down, reverse the list
t = t[::-1]

# for each line (currently a list of characters)
for l in t:
    # unpack the list into print as arguments, do not add a space between arguments
    print(*l,sep='')

```
> 0 votes

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


title: Group Integers by Originality

text:
# Question
Title: Group Integers by Originality
## Introduction:

I collect twisty puzzles. Most twisty puzzles are produced and sold by Chinese companies. Most well-known companies ask permission from puzzle designers to produce their designs and work together towards a product on the market. In this case, puzzle designers are of course very happy and proud that one of their puzzles hit the market.

There are however also Chinese companies which make knock-off puzzles. These knock-offs are either designs used without permission from the original creator, or are downright cheaper lower quality copies of already existing puzzles.

## Challenge:

We're going to determine the originality of numbers that are 'released' in a specific order (from left to right).
Given a list of integers, group and output them by their originality.

*How is the originality of the numbers determined?*

* Is a number an exact duplicate of an earlier number? Group \\$X+1\\$ (least original), where group \\$X+1\\$ is trailing, after all the other groups.
* Is a number a duplicate of an earlier number, but its negative instead (i.e. original number was \\$n\\$, but now \\$-n\\$; or vice-versa)? Group \\$X\\$.
* Can the absolute value of the number be formed by concatenating one or more earlier absolute numbers, and is it not part of the earlier mentioned groups \\$X+1\\$ or \\$X\\$? Group \\$X-N\\$, where \\$N\\$ is the amount of distinct numbers used in the concatenation (and \\$N\geq1\\$).
* Does the number not fit in any of the groups above, so is completely unique thus far? Group \\$1\\$ (most original), which is leading before all other groups.

This may sound pretty vague, so here **a step-by-step example**:

Input-list: `[34,9,4,-34,19,-199,34,-213,94,1934499,213,3,21,-2134,44449,44]`

* `34` is the first number, which is always original and in group \\$1\\$. Output thus far: `[[34]]`
* `9` is also original: `[[34,9]]`
* `4` is also original: `[[34,9,4]]`
* `-34` is the negative of the earlier number `34`, so it's in group \\$X\\$: `[[34,9,4],[-34]]`
* `19` is original: `[[34,9,4,19],[-34]]`
* `-199` can be formed by the two earlier numbers `19` and `9`, so it's in group \\$X-2\\$: `[[34,9,4,19],[-199],[-34]]`
* `34` is an exact copy of an earlier number, so it's in group \\$X+1\\$: `[[34,9,4,19],[-199],[-34],[34]]`
* `-213` is original: `[[34,9,4,19,-213],[-199],[-34],[34]]`
* `94` can be formed by the two earlier numbers `9` and `4`, so it's in group \\$X-2\\$: `[[34,9,4,19,-213],[-199,94],[-34],[34]]`
* `1934499` can be formed by the four earlier numbers `19`, `34`, `4`, and two times `9`, so it's in group \\$X-4\\$: `[[34,9,4,19,-213],[19499],[-199,94],[-34],[34]]`
* `213` is the negative of the earlier number `-213`, so it's in group \\$X\\$: `[[34,9,4,19,-213],[1934499],[-199,94],[-34,213],[34]]`
* `3` is original: `[[34,9,4,19,-213,3],[1934499],[-199,94],[-34,213],[34]]`
* `21` is original: `[[34,9,4,19,-213,3,21],[1934499],[-199,94],[-34,213],[34]]`
* `-2134` can be formed by the two earlier numbers `213` and `4` (or the three earlier numbers `21`, `3`, and `4`, but we always use the least amount of concatenating numbers to determine originality), so it's in group \\$X-2\\$: `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134],[-34,213],[34]]`
* `44449` can be formed by the two earlier numbers four times `4` and `9`, so it's in group \\$X-2\\$: `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[-34,213],[34]]`
* `44` can be formed by a single earlier number `4`, repeated two times, so it's in group \\$X-1\\$: `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[44],[-34,213],[34]]`

So for input `[34,9,4,-34,19,-199,34,-213,94,1934499,213,3,21,-2134,44449,44]` the output is `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[44],[-34,213],[34]]`.

## Challenge rules:

* I/O is flexible. You can input as a list/array/stream of integers or strings, input them one by one through STDIN, etc. Output can be a map with the groups as key, a nested list as the example and test cases in this challenge, printed newline separated, etc.
* You are allowed to take the input-list in reversed order (perhaps useful for stack-based languages). In which case the mentioned left-to-right is of course right-to-left.
* As you can see at the example for integer `-2134`, we always group a number that is a concatenation of other numbers with as few as possible (formed by `213` and `4` \- two numbers; and not by `21`, `3`, and `4` \- three numbers).
* As you can see at the example for integer `1934499`, you can use an earlier number (the `9` in this case) multiple times (similar with `44449` using four `4`s and a `9` in the example). They are only counted once for determining the group however.
* You are not allowed to have empty inner lists in the output for empty groups. So test case `[1,58,85,-8,5,8585,5885,518]` may not result in `[[1,58,85,8,5],[518],[5885],[8585],[],[]]` instead, where the empty groups are \\$X\\$ and \\$X-1\\$, and the example above may not result in `[[34,9,4,19,-213,3,21],[1934499],[],[-199,94,-2134,44449],[44],[-34,213],[34]]` instead, where the empty group is \\$X-3\\$.
* The order of the groups are strict (unless you use a map, since the groups can then be deducted from the keys), but the order of the numbers within a group can be in any order. So the `[34,9,4,19,-213,3,21]` for group \\$1\\$ in the example above can also be `[21,3,-213,19,4,9,34]` or `[-213,4,34,19,9,21,3]`.
* You are guaranteed that there will never be any numbers that can be formed by more than nine previous numbers. So you will never have any \\$X-10\\$ groups, and the largest amount of groups possible is 12: \\$\[1,X-9,X-8,...,X-2,X-1,X,X+1\]\\$
* You can assume the integers will be 32 bits at max, so within the range `[−2147483648,2147483647]`.

## General rules:

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

## Test cases:

```
Input:  [34,9,4,-34,19,-199,34,-213,94,1934499,213,3,21,-2134,44449,44]
Output: [[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[44],[-34,213],[34]]

Input:  [17,21,3,-317,317,2,3,117,14,-4,-232,-43,317]
Output: [[17,21,3,2,117,14,-4],[-317,-232,-43],[317],[3,317]]

Input:  [2,4,8,10,12,-12,-102,488,10824]
Output: [[2,4,8,10,12],[10824],[-102,488],[-12]]

Input:  [0,100,-100,10000,-100,1001000]
Output: [[0,100],[10000,1001000],[-100],[-100]]

Input:  [1,58,85,-8,5,8585,5885,518]
Output: [[1,58,85,-8,5],[518],[5885],[8585]]

Input:  [4,-4,44,5,54]
Output: [[4,5],[54],[44],[-4]]

```

# Answer
> 1 votes
# Jelly, ~~36~~ 33 bytes

```
ADṪŒṖfƑƇƊQ€Ẉ.*;,AṪe$€SƲṀµƤż⁸ṢZ¹ƙ/

```

Try it online!

I’m sure this can be golfed more. Some inspiration taken from Grimy’s 05AB1E answer, so be sure to upvote that one too!

# Answer
> 9 votes
# Python 3, ~~565~~ ~~564~~ ~~524~~ ~~523~~ ~~500~~ ~~437~~ ~~399~~ ~~394~~ ~~393~~ ~~389~~ ~~385~~ 372 bytes

Brute-force implementation using `itertools`; not all test-cases run within the 60 second limit on TIO.

Try it online!

Thanks to ArBo for golfing 101 bytes, to Galen Ivanov for golfing 19 bytes, to ElPedro for golfing 5 bytes, to movatica for golfing 17 bytes, to Black Owl Kai for golfing 2 bytes, to squid for golfing 2 bytes and to Kevin Cruijssen for golfing 1 byte.

```
from itertools import*
w=permutations
def c(l,x):
 for i in range(9):
  for q in w(map(abs,sum(l,[]))):
   for s in w(q[:i+1]*len(x)):
    z='';s=[*s]
    while x[len(z):]:
     z+=str(s.pop(0))
     if z==x:return 9-i
 return 0
def f(a):
 l=[[]for _ in a*6]
 for x in a:l[(x in sum(l,[]))*11or(-x in sum(l,[]))*10or any(l)and c(l,str(abs(x)))]+=x,
 return[*filter(len,l)]

```

Explanation:

```
from itertools import *
w = permutations  # We'll be using this twice

def c  # Helper function to calculate which group a number belongs in according to the concatenation rule; returns 0 (original) if none is found
(l, x):  # First parameter is the list of groups (a list of lists of numbers), second parameter is the number to investigate
 for i in range(9):  # There won't be any concatenations of more than 9 elements
  for q in w(map(abs,sum(l,[]))):  # Flatten l to get a plain list of previous numbers, then generate permutations of their absolute values as lists; for each permutation ...
   for s in w(q[:i+1]*len(x)):  # ... use only the first i + 1 elements; inflate the list with enough copies to compose the target number and permutate; then try to compose the target number from each permutation:
    z = ''  # Start with the empty string
    s = [*s]  # Convert permutation to list
    while x[len(z):]:  # Keep going until the length of the concatenated string equals the length of the target number
     z += str(s.pop(0))  # Concatenate the first element of the current permutation list and remove it
     if z == x:  # If the target number has been synthesized successfully ...
      return 9 - i  # stop searching and return the appropriate group
 return 0  # If no concatenation has been found, consider the number original

def f(a):  # Solution function, takes a list of numbers as argument
 l = [[] for _ in a * 6]  # Populate the result list with at least 12 empty groups if there is more than one number in the input (we'll be using only the first 12 and removing empty ones later); if there is just one, we'll only need one group in the output
 for x in a:  # For each number in order:
  l[(x in sum(l, [])) * 11 or (-x in sum(l, [])) * 10 or any(l) and c(l, str(abs(x)))] += x,  # If x is not the first number, attempt concatenation (if not, c(l, str(abs(x))) would crash due to l not containing any non-empty sublists; use absolute value of the number under investigation; convert to string since we'll be needing the number of digits and comparing it to a string later); if -x has already been seen, put it in Group X; if x has already been seen, put it in Group X + 1
  return [* filter(len, l)]  # Remove empty lists and return the result

```

# Python 2, ~~406~~ ~~379~~ ~~374~~ ~~373~~ ~~372~~ ~~368~~ 355 bytes

Same approach, but shorter due to some golfing tricks Python 3 doesn't support any more. Thanks to ArBo for the backport and for golfing 28 bytes, to ElPedro for golfing 5 bytes, to movatica for golfing 17 bytes, and to squid for golfing 1 more byte.

```
from itertools import*
w=permutations
def c(l,x):
 for i in range(9):
  for q in w(map(abs,sum(l,[]))):
	for s in map(list,w(q[:i+1]*len(x))):
	 z=''
	 while x[len(z):]:
		z+=`s.pop(0)`
		if z==x:return 9-i
 return 0
def f(a):
 l=[[]for _ in a*6]
 for x in a:l[(x in sum(l,[]))*11or(-x in sum(l,[]))*10or any(l)and c(l,`abs(x)`)]+=x,
 return filter(len,l)

```

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~43~~ ~~41~~ ~~38~~ ~~35~~ 27 bytes

```
.¡IN£UÄ.œεgΘ>XÄyÙå;P*}àXyå+

```

Try it online!

Explanation:

```
.¡                              # group by:
  IN£                           #  first N elements of the input, N being the iteration count
     U                          #  store this as X
  Ä                             #  absolute value of the current number
   .œ                           #  partitions (eg 449 => [[4, 4, 9], [44, 9], [4, 49], [449]])
     ε             }            #  map each partition to:
      gΘ>                       #   2 if length = 1, 1 otherwise
           yÙ                   #   for each unique element in the current partition:
         XÄ  å                  #    1 if it's in the absolute value of X, 0 otherwise
              ;                 #   divide all by 2
               P*               #   product of all these numbers
                  à             #  take the maximum
                   Xyå+         #  add 1 if X contains the current number

```

Since group numbers aren't part of the output, we're free to use any numbers we want, as long as the order is correct. This uses 0 for original numbers, 2^-N for group X-N, 1 for group X, 2 for group X+1.

# Answer
> 7 votes
# Python 2, ~~235~~ ~~234~~ ~~232~~ ~~246~~ ~~245~~ ~~244~~ ~~241~~ ~~240~~ ~~238~~ ~~237~~ 236 bytes

```
from itertools import*
s=[];r=map(list,[s]*12)
for e in input():r[-(e in s)or max([10*(-e in s)]+[10-len(set(p[:i]))for p in permutations(`abs(x)`for x in s*11)for i in range(len(p))if''.join(p[:i])==`e`])]+=e,;s+=e,
print filter(len,r)

```

Try it online!

-1 byte thanks to Squid's comment on the other Python answer

This answer has *no* hopes of solving any but the most trivial of test cases. In the TIO link, `s*11` has been replaced by `s*2`, sacrificing correctness in some cases for fast**er** execution time, but as far as I can see, the version in this post always yields the correct answer, in theory.

# Explanation

```
from itertools import*          # So that we can abuse permutations
s=[];                           # s will hold the already classified numbers
r=map(list,[s]*12)              # r will hold these too, but in the form of
                                #  a nested list, sorted by originality
for e in input():               # Here comes the big one; iterate over the input
 r[-(e in s)or                  # If e has already passed, it is not original
   max([10*(-e in s)]+          # Else, we count 10 - the number of seen elements
                                #  needed to make this one, or 0 if it's new,
                                #  or 10 if its inverse has already passed
   [10-len(set(p[:i]))          # The number of distinct elements in...
    for p in permutations(      #  for each permutation of the seen elements,
      `abs(x)`for x in s*11)
                                #  with values occuring up to 10 times (to
                                #  account for 1111111111, for example;
                                #  we need 11 here and not 10, because
                                #  p[:i] doesn't include i)...
    for i in range(len(p))      #  each prefix...
    if''.join(p[:i])            #  only if its concatenation is equal to
      ==`e`])]                  #  the current element
 +=e,;s+=e,                     # Append the element to the relevant lists
print filter(len,r)             # And finally, print the non-empty result lists

```

# Answer
> 2 votes
# Python 2, 195 bytes

The slowest test case can't complete on TIO, but it only takes about 10 seconds on my machine.

```
import re
a=[()];m=a*99
for n in input():
    i=0;r='-('
    while i<10>re.search(r'(\b.+\b).+'*i+r+')+$','%s-%%s'%a%n):i+=1;r+='|\\'+`i`
    m[48*(n in a)|32*(-n in a)|14-i]+=n,;a+=n,
print filter(len,m)

```

It can be shortened by 2 bytes on LP64 Python builds by replacing `'%s-%%s'%a%n` with ``a`+'-'+`n``.

# Answer
> 1 votes
# JavaScript (Node.js), ~~211~~ 205 bytes

```
a=>a.map(s=>(c[q=(G=(n,r=[],A=Math.abs,N=""+A(s))=>N[L="length"]<n[L]?0:N!=n?Math.max(0,...c.flat().map(x=>G(n+A(x),[...r,x]))):1/r?s-r?11:12:12+~new Set(r).size)``]=c[q]||[]).push(s),c=[])&&c.filter(x=>x)

```

Try it online!

Using the assumption that there are at most 12 groups.

# JavaScript (Node.js), ~~267~~ ~~226~~ ~~221~~ ~~218~~ 211 bytes

```
a=>a.map(s=>(c[q=(G=(n,r=[],A=Math.abs,N=""+A(s))=>N[L]<n[L]?0:N!=n?Math.max(0,...c.flat().map(x=>G(n+A(x),[...r,x]))):1/r?l-(s!=+r):l+~new Set(r).size)``]=c[q]||[]).push(s),c=[],l=a[L="length"])&&c.filter(x=>x)

```

Try it online!

```
a=>a.map(                       // Iterate through all items:
 s=>(c[q=(
  G=(                           //  Helper function to calculate index (=GroupNo-1):
   n,                           //   Stores different (repeatable) permutations
   r=[],                        //   Stores the elements used
   A=Math.abs,
   N=""+A(s))                   //   Stores the string version of the absolute value
  =>
  N[L="length"]<n[L]?           //   If n is longer then N:
   0                            //    0 (Group 1) - no permutation found to equal the string
  :N!=n?                        //   Else if N!=n:
   Math.max(0,...c.flat().map(  //    Return max of the results of the next recursion
    x=>G(n+A(x),[...r,x])       //    for each of the elements in c
   ))
  :1/r?                         //   Else if r has only 1 item: (=+s/-s)
   s-r?11:12                    //    Return l-1 (Group X) if r=-s, and l (Group X+1) if r=s
  :12+~new Set(r).size          //   Else: return l-r.size-1 (Group X-r.size)
 )``]=c[q]||[]).push(s),        //  Push the element into the corresponding array
 c=[]                           //  Initialize an empty array
)&&c.filter(x=>x)               // Filter out all empty groups

```

... or 193 bytes if returning a dictionary is okay:

```
a=>a.map(c=s=>(c[q=(G=(n,r=[],A=Math.abs,N=""+A(s))=>N[L="length"]<n[L]?-1/0:N!=n?Math.max(...d.map(x=>G(n+A(x),[...r,x]))):1/r?+!(s-r):-new Set(r).size)``]=c[q]||[]).push(s)&d.push(s),d=[])&&c

```

Try it online!

In this case, key `-Infinity` means Group 1 and other keys means Group `X+key`.

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