# Question
Title: I give you ascii-art, you make it pseudo-3d
Do you know the optical effect of a tridimensional hand painted whit horizontal lines? Examples

This challenge consists of making something like that effect with ascii, and transforming one 2d input into a "3d" output.

## The algorithm

To perform this transformation, you first replace all `1` with a `¯` and all `0` with a `_`. In order to make things more realistic, you should replace a `¯` that does not have another `¯` before it with `/`, and a `¯` that does not have another `¯` after it with `\`.

Some examples:

```
Input:
001111100

Output:
__/¯¯¯\__

```

```
Input:
0110
1111

Output:
_/\_
/¯¯\

```

^ In this case, there are multiple lines, so apply this to all lines.

```
Input:
000000000000000000000000000000000
000000111100000000000001111100000
000000111110000000000111111000000
000000111111000000011111100000000
000000111111000001111110000000000
000000011111100011111100000000000
000000111111111111111100000000000
000000111101111111011110000000000
000000111100111110011110000000000
000000111111111111111110000000000
000000111111111111111110000000000
000000001111111111110000000000000
000000000001111100000000000000000
000000000000000000000000000000000

Output:
_________________________________
______/¯¯\_____________/¯¯¯\_____
______/¯¯¯\__________/¯¯¯¯\______
______/¯¯¯¯\_______/¯¯¯¯\________
______/¯¯¯¯\_____/¯¯¯¯\__________
_______/¯¯¯¯\___/¯¯¯¯\___________
______/¯¯¯¯¯¯¯¯¯¯¯¯¯¯\___________
______/¯¯\_/¯¯¯¯¯\_/¯¯\__________
______/¯¯\__/¯¯¯\__/¯¯\__________
______/¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\__________
______/¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\__________
________/¯¯¯¯¯¯¯¯¯¯\_____________
___________/¯¯¯\_________________
_________________________________

```

Exceptions / rules:

* The input will never have a single positive cell in a row (e.g. `00100`)
* You can consider other characters for the input. However, it should only be two characters and not the same characters that the output uses. For instance:

```
Valid input:    0001111000 # two characters, different from the output
Valid input:    aaiiaiiaaa # two characters, different from the output
Valid input:    ,€€€€,,,,, # two characters, different from the output
Invalid input:  0001223000 # four different characters are used.
Invalid input:  ___1111___ # invalid, because the output uses underscores.
Invalid input:  ///\\\\/// # both slash and backslash are used by the output.

```
* The output must use the four characters described above and **only** those four. Alternatively, you may use `-` instead of the macron (`¯`)
* The macron (upper character) has a codepoint of 175, but you may count it as one byte.

This is , so the shortest code in bytes wins.

# Answer
> 12 votes
# Jelly, 16 bytes

```
Ż<ƝoḤU)⁺ị“\/Ø-_”

```

Try it online!

Uses hyphens instead of macrons. Takes a good deal of inspiration from hyper-neutrino's answer, so don't forget to send him some votes. Feels like there's got to be some way to shave a byte off the string at the end, with the right replacement for `oḤ`...

```
      )            For each line,
       ⁺           twice:
Ż                  prepend a 0,
  Ɲ                then for each pair of neighboring elements
 <                 is the second greater than the first?
   o               Replace zeroes with corresponding elements of
    Ḥ              the line doubled,
     U             and reverse.
        ị          Modular 1-index into
         “\/Ø-_    "\/Ø-_".
                   (0 -> _, 1 -> \, 2 -> /, 4 -> -)

```

# Answer
> 15 votes
# sed 4.2.2, Score 25

26 bytes, but scoring `¯` as 1, as per note in challenge.

```
s|1(1*)1|/\1\\|g
y/01/_¯/

```

Try it online!

# Answer
> 11 votes
# Retina 0.8.2, ~~26~~ 19 bytes

```
1(1*)1
/$.1$*¯\
0
_

```

Try it online! Link includes test cases. Edit: Saved 7 bytes with inspiration from @DigitalTrauma. Explanation:

```
1(1*)1
/$.1$*¯\

```

Replace a run of `1`s with a run of `¯`s between `/` and `\`.

```
0
_

```

Replace `0`s with `_`s.

(Note that Retina uses the ISO-8859-1 code page, so `¯` is 1 byte anyway.)

# Answer
> 8 votes
# Perl 5 (`-p -Mutf8`), 25 bytes, score 24

```
s|1(1*)1|/\1\\|g;y;01;_¯

```

Try it online!

Same as Digital Trauma's sed answer, except the trick using semicolon delimiter the last character can be removed.

# Answer
> 8 votes
# ///, 80 bytes

```
/0/_//1/a//aaa/a-a//-aa/--a//aa-/a--//-a-/---//a-/\\\/-//-a/-\\\\//aa/\\\/\\\\/

```

Try it online!

Uses `-` instead of the macron, as it is allowed.

I'm marking it as 80 bytes because of the required newline at the end of the input.

# Answer
> 8 votes
# Python 3.8 (pre-release), 80 bytes (but actually 79 because ¯ is counted as a 1 byte char in this challenge)

```
import re
while r:=re.sub:print(r(*"0_",r(*"1¯",r("1(1*)1",r"/\1\\",input()))))

```

Try it online!

Because we love `re.sub` :)

## Old solution : 94 bytes (but actually 93, you know the song ...)

I don't know why but I thought a pure vanilla python solution would beat a solution using regex ... I was wrong.

```
while r:=str.replace:print(r(r(r(r(f"0{input()}0","10","\\0"),"01","0/")[1:-1],*"1¯"),*"0_"))

```

Try it online!

Nothing too crazy here, just a few `str.replace`, and some `str.replace` and even more `str.replace`

# Answer
> 6 votes
# Jelly, 18 bytes

```
ŒgḤ1¦€N0¦€)ị“-/\_”

```

Try it online!

Inputs a matrix of `0` and `1`s, outputs a list of lines. Uses `-` instead of a macron

## How it works

```
ŒgḤ1¦€N0¦€)ị“-/\_” - Main link. Takes a matrix M on the left
          )        - Over each row R in M:
Œg                 -   Group adjacent equal elements in R
     €             -   Over each group G in R:
  Ḥ                -     Double:
   1¦              -     The first value
         €         -   Over each group G in R:
      N            -     Negate:
       0¦          -     The last value
                        For zeros, these are left unchanged.
                        For ones, the first becomes 2 and the last -1
            “-/\_” - Yield the string "-/\_"
           ị       - Index, 1 based and modularly. This means that:
                       1 or -3 -> -
                       2 or -2 -> /
                       3 or -1 -> \
                       4 or  0 -> _

```

# Answer
> 6 votes
# Jelly, 18 bytes

```
Ż;0ṡ3Ḅ)ị“_./__\-_”

```

Try it online!

Uses `-` instead of the macron

```
Ż;0ṡ3Ḅ)ị“_./__\-_”  Main Link; takes a matrix of bits and outputs a list of lines
      )             For each row
Ż                   Prepend 0
 ;0                 Append 0
   ṡ3               Get overlapping slices of length 3
     Ḅ              Convert from binary
                 // basically, the center of the 3-slice is the character itself
                 // and we need the left and right context to determine if it needs
                 // to be changed. So ___, __-, -__, and -_- (0, 1, 4, 5) become _,
                 // _-- (3) becomes /, --_ (6) becomes \, and --- (7) stays as -
       ị“_./_.\-_”  index into "_./_.\-_", so 1=_ 3=/ 4=_ 5=_ 6=\ 7=- 0=_
                 // note that Jelly is 1-indexed and indexes wrap around

```

# Answer
> 5 votes
# Excel (Insider Beta), ~~139~~ 96 bytes

```
=LET(s,LAMBDA(t,x,y,SUBSTITUTE(t,x,y)),s(s(s(s(s(A2,101,"\_/"),10,"\_"),0&1,"_/"),0,"_"),1,"-"))

```

Had to spend quite a few bytes shortening the `SUBSTITUTE` function. Originally, I thought you had to adapt to any two characters which is what I did below.

```
=LET(s,LAMBDA(t,x,y,SUBSTITUTE(t,x,y)),a,LEFT(A2),b,LEFT(s(s(A2,a,""),"
","")),s(s(s(s(s(A2,b&a&b,"\_/"),b&a,"\_"),a&b,"_/"),a,"_"),b,"-"))

```

# Answer
> 5 votes
# JavaScript (ES6), 54 bytes*

** by counting the macron as 1 byte, as allowed in this challenge*

```
s=>s.replace(/./g,(c,i)=>'_/¯\\'[c*=!+s[i+1]-~s[i-1]])

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 24 bytes

```
εγεS¬·0ǝR¬(0ǝR}˜"_¯/\"sè

```

Try it online! Takes input as a list of lines of ones and zeros and outputs as a list of lists of characters in each line.

```
εγεS¬·0ǝR¬(0ǝR}˜"..."sè  # trimmed program
                         # implicit input...
ε                        # with each element replaced by...
                      è  # list of characters in...
                "..."s   # literal...
                      è  # with indices in...
               ˜     s   # flattened...
 γ                       # list of groups of consecutive equal elements in...
                         # (implicit) current element in map...
  ε                      # with each element replaced by...
             R           # reversed...
        R                # reversed...
   S                     # list of characters in...
                         # (implicit) current element in map...
       ǝ                 # with element at index...
      0                  # literal...
       ǝ                 # replaced with...
    ¬                    # first element of...
   S                     # list of characters in...
                         # (implicit) current element in map...
     ·                   # doubled...
             ǝ           # with element at index...
            0            # literal...
             ǝ           # replaced with...
          ¬              # first element of...
        R                # reversed...
   S                     # list of characters in...
                         # (implicit) current element in map...
       ǝ                 # with element at index...
      0                  # literal...
       ǝ                 # replaced with...
    ¬                    # first element of...
   S                     # list of characters in...
                         # (implicit) current element in map...
     ·                   # doubled...
           (             # negated
               }         # exit map
                         # (implicit) exit map
                         # implicit output

```

`R}` can also be a  with no change in functionality: Try it online!

# Answer
> 4 votes
# Pip `-rl`, 21 "bytes"

```
gR+X1'/.TM_.'\TRt"¯_"

```

Try it online!

### Explanation

```
g                      With -r flag, g is a list of all lines from stdin
 R                     In each line, replace
  +X1                   regex match of one or more 1's
                        with this callback function:
        TM_              Trim the first and last characters from the match
     '/.                 Prepend /
           .'\           Append \
              TR       Transliterate
                t      10
                 "¯_"  into ¯_
                       Autoprint, one list element per line (-l flag)

```

# Answer
> 4 votes
# Vyxal `aṠD`, 21 bytes

*-1 from Aaron Miller*

```
ƛĠƛ⌊ḣ$NpṫdJ`_¯\/`$İ;f

```

Try it Online!

Heavily inspired by @caird coinheringaahing's Jelly answer.
Outputs a list of lines containing a list of characters in each line. Uses the actual macron!

```
ƛĠƛ⌊ḣ$NpṫdJ`_¯\/`$İ;f
ƛ                       For each line of (implicit) input...
 Ġƛ                ;     For each group of consecutive characters...
   ⌊                      Convert each character to an integer (so double and negate work)
      N                   Negate...
    ḣ$ p                    the first element of the group.
         d                Double...
        ṫ J                 the last element of the group.
                  İ       Index each element...
           `_¯\/`$          in "_¯\/" (negative indices start from the back)
                    f    Flatten the list of groups to a lists of chars

```

# Answer
> 3 votes
# , 48 44 43 41 bytes

```
'_^/\'{~(>./@,+:@g&.|.,:3*g=.1=2-/\,&0)"1

```

Try it online!

# Answer
> 3 votes
# AWK, 56 bytes, 54 by the rules

```
gsub(0,"_")gsub(1,"/\\")gsub(/\\\//,"¯")gsub("/¯","/")

```

Try it online!

Substitutes: all `0` to `_`; all `1` to `/\`; all `\/` to `¯`; and, finally, all  to `/`.

# AWK, 52 bytes, 51 by the rules

```
gsub("01","0/")gsub(10,"\\0")gsub(0,"_")gsub(1,"¯")

```

Try it online!

Thanks to DLsoc for a 52 bytes/51 characters version.

# Answer
> 3 votes
# 05AB1E, 17 bytes

```
γε¬i¦¦…/ÿ\]JT„¯_‡

```

I/O as a multiline string.

Try it online.

**Explanation:**

```
γ           # Split the (implicit) input-string into equal adjacent parts
            #  i.e. "0110\n1111" → ["0","11","0","\n","1111"]
 ε          # Map each part to:
  ¬         #  Get its first character (without popping)
   i        #  If this is a 1:
    ¦¦      #   Remove two characters from this string
      …/ÿ\  #   Surround it with leading "/" and trailing "\"
 ]          # Close both the if-statement and map
            #  → ["0","/\","0","\n","/11\"]
  J         # Join everything back together
            #  → "0/\0\n/11\"
   T   ‡    # Then transliterate the characters "1" and "0"
    „¯_     # to the characters "¯" and "_"
            #  → "_/\_\n/¯¯\"
            # (after which the result is output implicitly)

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~71 65~~ 61 bytes

```
n=>n.replace(/./g,(e,i)=>+e?+n[i+1]?+n[i-1]?'-':'/':'\\':'_')

```

Try it online!

## How it works

Replaces every letter. For each letter in question: if the numerical representation is falsy (`0`) then replace with `_`, otherwise use a simple ternary to find the correct character to use. Uses `-` instead of macron, you know, just because. Saved 6 bytes by reorganizing and removing assignment to unused `a` variable. Then saved 4 thanks to a username by entirely getting rid of variables.

# Answer
> 2 votes
# Charcoal, 20 bytes

```
ＷＳ⟦⪫Ｅ⪪ι0∧κ⪫/\×¯⁻Ｌκ²_

```

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

```
ＷＳ⟦

```

Loop over each input string and print each output on a new line until an empty line is reached. (String array input format would have saved a byte.)

```
⪫Ｅ⪪ι0∧κ⪫/\×¯⁻Ｌκ²_

```

Split each string on `0`s, then replace each (non-empty) run of `1`s with a run of `¯`s wrapped in `/` and `\`, finally joining with `_`s.

# Answer
> 2 votes
# Stax, 19 bytes

```
√E6∙²δ♪₧♂─Ç,áR0Z◄@╖

```

Run and debug it

A regex based solution similar to the Pip and sed answers. Takes a full multiline string.

# Answer
> 2 votes
# Mathematica,  74 bytes

```
StringReplace[#,{"101"->"\_/","01"->"_/","10"->"¯\\","0"->"_","1"->"¯"}]&

```

---
Tags: code-golf, ascii-art, unicode, 3d
---


title: Peter is Puzzled!

text:
# Question
Title: Peter is Puzzled!
As some of you may remember, Peter, who was a picky eater is now puzzled Peter.

This time Peter got some puzzles as a present from his Aunt. He has tried a lot, but has failed to solve the puzzles. Peter needs your help to solve them.

Each one of the puzzle has 2 pieces. To solve the puzzle, you must tell the number of ways piece 1 can fit into the empty spaces in Piece 2. We can safely assume that both the pieces cannot be rotated.

For example,

```
Piece 1:
.#
##
.#

Piece 2:

#..#######
#.##..####
###..##...
####.#####
##.#######
##......##
##.....###
########..

```

There is only 1 possible way to fit Piece one into Piece 2:

```
#..#######
#.##*.####
###**##...
####*#####
##.#######
##......##
##.....###
########..

```

Hence, the output must be \\$1\\$.

## Input

You may take the input as a binary matrix of 1's and 0's, or as a string with empty spaces and filled spaces as characters of your choice.

Piece 1 is not always a solid piece, it may or may not be connected.

## Output

An integer \\$n\\$ for the number of ways to fit Piece 1 in Piece 2. If there are no ways, you may return \\$0\\$ or any other non-integer value.

## Test Cases

```
All inputs formatted as a 2d array, with each inner array representing a row in the puzzle. 0 represents empty gap, 1 represents filled space.

Piece 1: [[0, 1], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]
Output: 1

Piece 1: [[1, 0], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1, 0, 0]]
Output: 1

Piece 1: [[1, 1]]
Piece 2: [[0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 0, 0], [1, 1, 0, 1]]
Output: 4

Piece 1: [[1, 1, 1]]
Piece 2: [[0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]
Output: 4

Piece 1: [[0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
Output: 1

Piece 1: [[1, 0, 0], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 42

Piece 1: [[1, 0, 1], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 35

Piece 1: [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
Piece 2: [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1]]
Output: 1

Piece 1: [[1]]
Piece 2: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
Output: 0 (Or any other non-integer value)

```

## Winning criteria

this is so shortest answer, in each language wins.

# Answer
# MATL, 11 bytes

*Thanks to @att for pointing out a mistake, now corrected.*

```
,XP!]&2Y+~z

```

Inputs piece 1, then piece 2 as binary matrices.

Try it online! Or verify all test cases.

### Explanation

> Convolution is the key to success

This computes the 2D-convolution of piece 2 and a vertically and horizontally flipped version of piece 1, keeping only the results that assume no zero padding of piece 2. What the convolution does is:

* Piece 1 is flipped vertically and horizontally, which undoes the previous flipping of this piece; then
* it is shifted in the two dimensions, traversing all positions so that it doesn't move "outside" of piece 2. For each position,
* corresponding entries of both pieces are multiplied, and
* the sum of all those products is computed.

Piece 1 fits in a given position if and only if the sum computed as above is 0, meaning that all `1` entries of piece 1 coincide with a `0` of piece 2.

```
,      % Do twice
  XP   %   Implicitly inputs piece 1 the first time. Flip vertically
  !    %   Transpose
]      % End
&2Y+   % Implicitly inputs piece 2. 2D convolution, only 'valid' part
~z     % Number of zeros. Implicitly displays the result

```
> 9 votes

# Answer
# , 23 bytes

```
4 :'+/,x(-:y<]);._3~$y'

```

Try it online!

(Tacit for 24b: `[:+/@,](]-:<)"2([;._3~$)`)

For each tile `u;._3~` of the size of the piece `$y`, is no position blocked? (Tile still equal to itself `-:` when comparing each position from the piece with the tile `y<]`?) Sum the result `+/,`.
> 5 votes

# Answer
# APL (Dyalog Unicode), 24 bytes

Anonymous infix lambda taking Piece 1 as left argument Boolean matrix of needed positions, and Piece 2 as right argument Boolean matrix of *available* positions. Requires 0-based indexing (`⎕IO←0`).

```
{≢⍸∧/⍵[(⍳1+⍵-⍥⍴⍺)∘.+⍸⍺]}

```

Try it online! (using a polyfill for  since TIO is stuck on version 17.1)

`{``}` "dfn"; left and right arguments are  and :

`⍵[``]` index into  to get the elements at the following positions:

`⍸⍺` list of true-coordinates in

`(``)∘.+` outer sum (i.e. all addition combinations with):

`⍵-⍥⍴⍺` the difference in shapes between Piece 2 and Piece 1

`1+` increment

all indices of an array of that size

`∧/` AND-reduction along the trailing axis (computes where all required slots are available)

indices of available placements

tally those

---

I'm a bot, so my owner posted this for me.
> 4 votes

# Answer
# Python 3, 85 ~~109~~ bytes

```
from numpy import*
from scipy.signal import*
lambda a,b:sum(correlate(a,b,'valid')<1)

```

`correlate` needs `scipy.signal` for 2d arrays and will give back `0` for matching positions, using `numpy.count_nonzero` with the condition will give back the number of zeroes which is the expected result.

Edit1: changed `count_nonzero` to `sum`, removed `array` conversions

Try it online!
> 3 votes

# Answer
# Jelly, 19 bytes

```
ṡ€ZL$}¹ṡL}Z€Ẏa€¬Ȧ€S

```

Try it online!

-1 byte thanks to Nick Kennedy

```
ṡ€ZL$}¹ṡL}Z€Ẏa€¬Ȧ€S    Main Link; accept piece 2 on the left and piece 1 on the right
ṡ€                     Get all overlapping slices of piece 2 of length
  ZL$}                 Width of piece 1
      ¹                (Identity)
       ṡ               Slice this into overlapping pieces of length
        L}             Height of piece 1
          Z€           Transform each to get it to the correct orientation
            Ẏ          Flatten once; we now have a list of 2D blocks in piece 2
             a€        Logical AND with piece 1 (vectorizing); gives intersection areas
               ¬       Logical NOT (vectorize)
                Ȧ€     For each chunk, check if all are truthy (i.e. none were truthy initially; 1 if it fits, 0 otherwise)
                  S    Sum; count number of positions that fit

```
> 3 votes

# Answer
# JavaScript (ES6), 95 bytes

Expects two binary matrices as `(a)(b)`.

```
a=>b=>b.map((r,y)=>r.map((_,x)=>t+=!a.some((r,Y)=>r.some((v,X)=>v&(b[y+Y]||0)[x+X]!=0))),t=0)|t

```

Try it online!

Or 92 bytes with optional chaining (doesn't work on TIO).
> 3 votes

# Answer
# Python 3, 138 bytes

```
lambda a,b,l=len:sum(all(q&p^1for Q,P in zip(a,b[i:])for q,p in zip(Q,P[j:]))for i in range(l(b)-l(a)+1)for j in range(l(b[0])-l(a[0])+1))

```

Try it online!

## Ungolfed :

```
def f(a,b):
  s=0 # intitialise the counter
  for i in range(len(b)-len(a)+1): # iterate through all the lines
    for j in range(len(b[0])-len(a[0])+1): # iterate through all the column
      # verify if the piece can fit
      if all(a[k][l]&b[i+k][j+l]^1 for k in range(len(a))for l in range(len(a[0]))):
        s+=1 # increase the counter
  return s  # return the counter

```

Try it online!

* `q&p^1` will be equal to 1 only if at most 1 of `q` and `p` is equal to 1
> 2 votes

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

```
(a,b,d=b[z=0][L='length'],F=a.flat())=>b.flat().map((e,i)=>z+=b.slice(i/d,i/d+a[L]).flatMap((l,c)=>l.slice(i%d,i%d+a[0][L])).every((l,c,A)=>A[L]==F[L]&&!l|F[c]<l))|z

```

Try it online!

This feels too long.

Calculate the number of items in flattened `b` (second piece) that satisfy the conditions: the `a`-sized tile with that item as the top-left corner is equal to `a` and fits in `b`.

Credits: @EliteDaMyth (see comments)
> 1 votes

# Answer
# Charcoal, 46 bytes

```
≔⟦⟧ηＷＳ⊞ηιＷＳ⊞υ⁺ι⭆θ#Ｆη⊞υ#ＩΣ⭆υ⭆ι⬤η⬤ν№⁺π§§υ⁺κξ⁺μρ.

```

Try it online! Link is to verbose version of code. Takes input as two newline-terminated lists of strings of `.` and any other character. Explanation:

```
≔⟦⟧ηＷＳ⊞ηι

```

Input piece 1.

```
ＷＳ⊞υ⁺ι⭆θ#Ｆη⊞υ#

```

Input piece 2, but pad it so that piece 1 can't accidentally wrap around (this is slightly golfier than calculating the positions that won't wrap around).

```
ＩΣ⭆υ⭆ι⬤η⬤ν№⁺π§§υ⁺κξ⁺μρ.

```

Count the number of possible positions of piece 1 in piece 2 where for all of the overlapping squares at least one of them is a `.`.
> 0 votes

# Answer
# JavaScript, 108 bytes

```
a=>b=>[...b.matchAll(`(?=${a.replace(/./sg,c=>[`[
21]{${b.search`
`-a.search`
`+1}}`,'.',1][+c])})`)].length

```

```
f =

a=>b=>[...b.matchAll(`(?=${a.replace(/./sg,c=>[`[
21]{${b.search`
`-a.search`
`+1}}`,'.',1][+c])})`)].length

testcases = `
Piece 1: [[0, 1], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]
Output: 1

Piece 1: [[1, 0], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1, 0, 0]]
Output: 1

Piece 1: [[1, 1]]
Piece 2: [[0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 0, 0], [1, 1, 0, 1]]
Output: 4

Piece 1: [[1, 1, 1]]
Piece 2: [[0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]
Output: 4

Piece 1: [[0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
Output: 1

Piece 1: [[1, 0, 0], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 42

Piece 1: [[1, 0, 1], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 35

Piece 1: [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
Piece 2: [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1]]
Output: 1

Piece 1: [[1]]
Piece 2: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
Output: 0 (Or any other non-integer value)
`.trim().split('\n\n').map(t => t.split('\n').map(l => JSON.parse(l.replace(/^.*:|\(.*$/g, '')))).map(([a, b, e]) => [a.map(l => l.map(n => '12'[n]).join('')).join('\n'), b.map(l => l.map(n => '12'[n]).join('')).join('\n'), e]);

testcases.forEach(([a, b, e]) => { console.log(f(a)(b) === e, f(a)(b)); });
```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 28 bytes

```
Count[ListCorrelate@##,0,2]&

```

Try it online!
> 0 votes

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


title: Full name quine

text:
# Question
Title: Full name quine
Most Unicode characters have full names, for example  is "RIGHT DOUBLE QUOTATION MARK". You can find a useful reference here, just type in the character you want to find the full name of and look in the DESCRIPTION column.

Your challenge is to write a program or function that outputs itself as a string of these. You can output as an array, or space/newline separated.

# Scoring

This challenge is scored in *characters* instead of bytes - Least characters wins!

You can only use characters with descriptions other than `U+(Whatever)`, so  and similar are banned.

External resources *are* allowed, but those without are generally more interesting.

# Answer
> 14 votes
# Raku, 37 characters

```
<print "<$_>~~.EVAL".uninames>~~.EVAL

```

Try it online!

Variation of the standard Raku quines using `print` to avoid the trailing newline and `.uninames` to convert to a list of character names.

# Answer
> 11 votes
# JavaScript, 440 bytes

```
f=a=>[..."f="+f].map(n=>({"(":(l="LEFT ")+(p="PARENTHESIS"),")":(r="RIGHT ")+p,"{":l+(c="CURLY"+(b=" BRACKET")),"}":r+c,"[":l+(q="SQUARE"+b),"]":r+q,"=":"EQUALS"+(s=" SIGN"),">":"GREATER-THAN"+s,"+":"PLUS"+s,"\\":"REVERSE SOLIDUS","\"":"QUOTATION MARK","&":"AMPERSAND",".":"FULL STOP",",":"COMMA",":":"COLON"," ":"SPACE","-":"HYPHEN-MINUS","|":"VERTICAL LINE"}[n]||"LATIN "+(n>{}&&"SMALL"||"CAPITAL")+" LETTER "+n.toUpperCase())).join("\n")

```

Try it online!

# Answer
> 11 votes
# Haskell, 642 bytes

```
f" "="SPACE";f"\""="QUOTATION MARK";f"."="FULL STOP";f";"="SEMICOLON";f"<"="LESS-THAN SIGN";f"="="EQUALS SIGN";f">"="GREATER-THAN SIGN";f"\\"="REVERSE SOLIDUS";f"-"="HYPHEN-MINUS";f x="LATIN "<>if x>"Z"then"SMALL LETTER "<>x else"CAPITAL LETTER "<>x;u=putStrLn.f.pure;s=id<>show;n=mapM u.s;main=n"f\" \"=\"SPACE\";f\"\\\"\"=\"QUOTATION MARK\";f\".\"=\"FULL STOP\";f\";\"=\"SEMICOLON\";f\"<\"=\"LESS-THAN SIGN\";f\"=\"=\"EQUALS SIGN\";f\">\"=\"GREATER-THAN SIGN\";f\"\\\\\"=\"REVERSE SOLIDUS\";f\"-\"=\"HYPHEN-MINUS\";f x=\"LATIN \"<>if x>\"Z\"then\"SMALL LETTER \"<>x else\"CAPITAL LETTER \"<>x;u=putStrLn.f.pure;s=id<>show;n=mapM u.s;main=n"

```

Try it online!

# Answer
> 7 votes
# Python 2, 68 characters

Based on this quine.

```
s="from unicodedata import*;print map(name,u's=%r;exec s'%s)";exec s

```

Try it online!

# Answer
> 4 votes
# JavaScript (browser), 365 characters

```
(f=async _=>{i='';for(e of `(f=${f})()`)i+=await fetch(`https://unicode-search.net/unicode-namesearch.pl?term=${e}&.submit=Search`).then(r=>r.text()).then(s=>(/[a-zA-Z]/.test(e)?`LATIN ${/[a-z]/.test(e)?'SMAL':'CAPITA'}L LETTER `+e.toUpperCase():s.substr(S=s.search(/(?<=class\="name" (colspan\="."|lang\="en")>)/),s.slice(S).search(`<\/`)))+' ');console.log(i)})()

```

This took a really long time to write. Outputs

```
LEFT PARENTHESIS LATIN SMALL LETTER F EQUALS SIGN LATIN SMALL LETTER A LATIN SMALL LETTER S LATIN SMALL LETTER Y LATIN SMALL LETTER N LATIN SMALL LETTER C SPACE LOW LINE EQUALS SIGN GREATER-THAN SIGN LEFT CURLY BRACKET LATIN SMALL LETTER I EQUALS SIGN APOSTROPHE APOSTROPHE  LATIN SMALL LETTER F LATIN SMALL LETTER O LATIN SMALL LETTER R LEFT PARENTHESIS LATIN SMALL LETTER E SPACE LATIN SMALL LETTER O LATIN SMALL LETTER F SPACE GRAVE ACCENT LEFT PARENTHESIS LATIN SMALL LETTER F EQUALS SIGN DOLLAR SIGN LEFT CURLY BRACKET LATIN SMALL LETTER F RIGHT CURLY BRACKET RIGHT PARENTHESIS LEFT PARENTHESIS RIGHT PARENTHESIS GRAVE ACCENT RIGHT PARENTHESIS LATIN SMALL LETTER I SPACE EQUALS SIGN LATIN SMALL LETTER A LATIN SMALL LETTER W LATIN SMALL LETTER A LATIN SMALL LETTER I LATIN SMALL LETTER T SPACE LATIN SMALL LETTER F LATIN SMALL LETTER E LATIN SMALL LETTER T LATIN SMALL LETTER C LATIN SMALL LETTER H LEFT PARENTHESIS GRAVE ACCENT LATIN SMALL LETTER H LATIN SMALL LETTER T LATIN SMALL LETTER T LATIN SMALL LETTER P LATIN SMALL LETTER S COLON SOLIDUS SOLIDUS LATIN SMALL LETTER U LATIN SMALL LETTER N LATIN SMALL LETTER I LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER D LATIN SMALL LETTER E HYPHEN-MINUS LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H FULL STOP LATIN SMALL LETTER N LATIN SMALL LETTER E LATIN SMALL LETTER T SOLIDUS LATIN SMALL LETTER U LATIN SMALL LETTER N LATIN SMALL LETTER I LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER D LATIN SMALL LETTER E HYPHEN-MINUS LATIN SMALL LETTER N LATIN SMALL LETTER A LATIN SMALL LETTER M LATIN SMALL LETTER E LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H FULL STOP LATIN SMALL LETTER P LATIN SMALL LETTER L QUESTION MARK LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER R LATIN SMALL LETTER M EQUALS SIGN DOLLAR SIGN LEFT CURLY BRACKET LATIN SMALL LETTER E RIGHT CURLY BRACKET  FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER U LATIN SMALL LETTER B LATIN SMALL LETTER M LATIN SMALL LETTER I LATIN SMALL LETTER T EQUALS SIGN LATIN CAPITAL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H GRAVE ACCENT RIGHT PARENTHESIS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER H LATIN SMALL LETTER E LATIN SMALL LETTER N LEFT PARENTHESIS LATIN SMALL LETTER R EQUALS SIGN GREATER-THAN SIGN LATIN SMALL LETTER R FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER X LATIN SMALL LETTER T LEFT PARENTHESIS RIGHT PARENTHESIS RIGHT PARENTHESIS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER H LATIN SMALL LETTER E LATIN SMALL LETTER N LEFT PARENTHESIS LATIN SMALL LETTER S EQUALS SIGN GREATER-THAN SIGN LEFT PARENTHESIS SOLIDUS LEFT SQUARE BRACKET LATIN SMALL LETTER A HYPHEN-MINUS LATIN SMALL LETTER Z LATIN CAPITAL LETTER A HYPHEN-MINUS LATIN CAPITAL LETTER Z RIGHT SQUARE BRACKET SOLIDUS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER S LATIN SMALL LETTER T LEFT PARENTHESIS LATIN SMALL LETTER E RIGHT PARENTHESIS QUESTION MARK GRAVE ACCENT LATIN CAPITAL LETTER L LATIN CAPITAL LETTER A LATIN CAPITAL LETTER T LATIN CAPITAL LETTER I LATIN CAPITAL LETTER N SPACE DOLLAR SIGN LEFT CURLY BRACKET SOLIDUS LEFT SQUARE BRACKET LATIN SMALL LETTER A HYPHEN-MINUS LATIN SMALL LETTER Z RIGHT SQUARE BRACKET SOLIDUS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER S LATIN SMALL LETTER T LEFT PARENTHESIS LATIN SMALL LETTER E RIGHT PARENTHESIS QUESTION MARK APOSTROPHE LATIN CAPITAL LETTER S LATIN CAPITAL LETTER M LATIN CAPITAL LETTER A LATIN CAPITAL LETTER L APOSTROPHE COLON APOSTROPHE LATIN CAPITAL LETTER C LATIN CAPITAL LETTER A LATIN CAPITAL LETTER P LATIN CAPITAL LETTER I LATIN CAPITAL LETTER T LATIN CAPITAL LETTER A APOSTROPHE RIGHT CURLY BRACKET LATIN CAPITAL LETTER L SPACE LATIN CAPITAL LETTER L LATIN CAPITAL LETTER E LATIN CAPITAL LETTER T LATIN CAPITAL LETTER T LATIN CAPITAL LETTER E LATIN CAPITAL LETTER R GRAVE ACCENT SPACE LATIN SMALL LETTER E FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER O LATIN CAPITAL LETTER U LATIN SMALL LETTER P LATIN SMALL LETTER P LATIN SMALL LETTER E LATIN SMALL LETTER R LATIN CAPITAL LETTER C LATIN SMALL LETTER A LATIN SMALL LETTER S LATIN SMALL LETTER E LEFT PARENTHESIS RIGHT PARENTHESIS COLON LATIN SMALL LETTER S FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER U LATIN SMALL LETTER B LATIN SMALL LETTER S LATIN SMALL LETTER T LATIN SMALL LETTER R LEFT PARENTHESIS LATIN CAPITAL LETTER S EQUALS SIGN LATIN SMALL LETTER S FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H LEFT PARENTHESIS SOLIDUS LEFT PARENTHESIS QUESTION MARK LESS-THAN SIGN EQUALS SIGN LATIN SMALL LETTER C LATIN SMALL LETTER L LATIN SMALL LETTER A LATIN SMALL LETTER S LATIN SMALL LETTER S REVERSE SOLIDUS EQUALS SIGN QUOTATION MARK LATIN SMALL LETTER N LATIN SMALL LETTER A LATIN SMALL LETTER M LATIN SMALL LETTER E QUOTATION MARK SPACE LEFT PARENTHESIS LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER L LATIN SMALL LETTER S LATIN SMALL LETTER P LATIN SMALL LETTER A LATIN SMALL LETTER N REVERSE SOLIDUS EQUALS SIGN QUOTATION MARK FULL STOP QUOTATION MARK VERTICAL LINE LATIN SMALL LETTER L LATIN SMALL LETTER A LATIN SMALL LETTER N LATIN SMALL LETTER G REVERSE SOLIDUS EQUALS SIGN QUOTATION MARK LATIN SMALL LETTER E LATIN SMALL LETTER N QUOTATION MARK RIGHT PARENTHESIS GREATER-THAN SIGN RIGHT PARENTHESIS SOLIDUS RIGHT PARENTHESIS COMMA LATIN SMALL LETTER S FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER L LATIN SMALL LETTER I LATIN SMALL LETTER C LATIN SMALL LETTER E LEFT PARENTHESIS LATIN CAPITAL LETTER S RIGHT PARENTHESIS FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H LEFT PARENTHESIS GRAVE ACCENT LESS-THAN SIGN REVERSE SOLIDUS SOLIDUS GRAVE ACCENT RIGHT PARENTHESIS RIGHT PARENTHESIS RIGHT PARENTHESIS SPACE APOSTROPHE SPACE APOSTROPHE RIGHT PARENTHESIS  LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER N LATIN SMALL LETTER S LATIN SMALL LETTER O LATIN SMALL LETTER L LATIN SMALL LETTER E FULL STOP LATIN SMALL LETTER L LATIN SMALL LETTER O LATIN SMALL LETTER G LEFT PARENTHESIS LATIN SMALL LETTER I RIGHT PARENTHESIS RIGHT CURLY BRACKET RIGHT PARENTHESIS LEFT PARENTHESIS RIGHT PARENTHESIS

```

using unicode-search.net.

-7 chars to fix small bug. No, that's not a typo, I actually *saved* characters fixing a bug which made all small letters "CAPITAL".

# Answer
> 4 votes
# JavaScript, ~~144~~ 102 bytes

Needs to be run in the browser console from this page as permitted here. Returns an array of promises containing the character names as permitted here. +12 bytes to fix a bug with spaces :\

```
f=_=>[...`f=`+f].map(async c=>(await(await fetch(`?a=`+(c==` `?20:c))).text()).match(/me'>(.+?)</)[1])

```

# Answer
> 4 votes
# Jelly, ~~66~~ 64 bytes

```
“__import__('unicodedata').name(*'''“ ''')“jⱮṾ;ṪƊŒV€Y”jⱮṾ;ṪƊŒV€Y

```

Try it online!

*-2 bytes by splicing and splatting instead of using `string`*

This still feels... easily outdone. Probably using `v`.

```
“...“...“jⱮṾ;ṪƊŒV€Y”              Operate on this list of three strings.
                      Ṿ           Get its string representation
                       ;          and concatenate
                        Ṫ         and pop its last element;
                     Ɱ   Ɗ        for each character of that result
                    j             join the remaining two elements on it.
                          ŒV€     Evaluate each as Python,
                             Y    and join the values on newlines.

```

In order to place a literal single quote inside the Python code and use it as such, we can't use `'\“'` because most other characters will either result in an unwanted incorrect escape sequence or an actual backslash and a `TypeError`, we can't use `"“"` because now we just have the same problem with double quotes, and we can't use `'''“'''` because `'''''''` parses as `'''''' '` resulting in a `SyntaxError`. `'''“ '''[0]` only breaks even with the previous version, but fortunately `unicodedata.name` can take an optional second argument--a default for if the character given does not have a name--so we can use the splat operator `*` to send the unwanted space there for two less bytes.

# Answer
> 3 votes
# Perl 5, 63 bytes

```
$_=q(say charnames::viacode(ord)for"\$_=q($_);eval"=~/./g);eval

```

Try it online!

# Answer
> 3 votes
# Java (JDK), 156 bytes

```
v->{var s="v->{var s=%c%s%1$c;return s.format(s,34,s).chars().mapToObj(Character::getName);}";return s.format(s,34,s).chars().mapToObj(Character::getName);}

```

Try it online!

Takes a `null` input and returns a `Stream<String>`.

---
Tags: code-golf, quine, unicode
---


title: Draw a mountain given altitude

text:
# Question
Title: Draw a mountain given altitude
Take an array of nonnegative integers, such as `[1, 0, 0, 1, 2, 4, 2, 0]`. Then, draw that as a mountain where the integers represent altitude:

```
     x

    x x
x  x
 xx    x

```

You may use any printable non-whitespace character in place of `x`, and adding padding or whitespace after lines or the output is fine (but not required). You may optionally take one indexed inputs. Transposing the output is not allowed, but returning an array of lines is fine.

This is , so shortest answer (in bytes) per language wins.

# Answer
> 17 votes
# Vyxal, 4 bytes

```
×꘍R§

```

Try it Online!

That's right, it's flagless.

## Explained

```
×꘍    # [(n * " ") + "*" for n in input]
  R   # [x[::-1] for x in ^]
   §  # vertically join (rotate) ^

```

Using the `L` flag would make it 3 bytes.

# Answer
> 11 votes
# Python 2, 66 bytes

```
a=input()
n=max(a)
while~n:print''.join(' x'[x==n]for x in a);n-=1

```

Try it online!

# Answer
> 9 votes
# 05AB1E (legacy), 5 bytes

```
$úζR»

```

Try it online!

```
$        # push "1" and the input
 ú       # for each integer in the input,
         # pad "1" with this many spaces in the front
  ζ      # tranpose, padding with spaces
   R     # reverse, the mountains should not be upside down
    »    # join by newlines

```

# Answer
> 7 votes
# Zsh, ~~66~~ 63 bytes

```
s=${(l/${${(On)@}[1]}*#/)}
for x;s[++i+$#s-#*x]=.
fold -$#<<<$s
```

Attempt This Online!

-3 thanks to JoKing, but still probably too long.

Explanation:

* `${${(On)@}[1]}`: get the maximum input
* `s=${(l/*#/)}`: construct a string of spaces which is (number of inputs) × (maximum of inputs) in length
* `for x;s[++i+$#s-#*x]=.`: set the correct index of the string to a `.` for each element
* `fold -$#<<<$s`: line-wrap the string at (number of inputs) in length

# Answer
> 6 votes
# APL(Dyalog Unicode), 18 bytes SBCS

```
{⊖⍉⍕⍪'x',¨⍨⍵⍴¨' '}

```

```
{          ⍝ Open function
⊖⍉         ⍝ Flip diagonally and then vertically
⍕          ⍝ Make table into multiline string
⍪           ⍝ Display one element per row
'x',¨⍨      ⍝ Append an 'x' to each element
⍵⍴¨' '      ⍝ Duplicate each space 'input' times
}           ⍝ Close function

```

Try it on online!

# Answer
> 6 votes
# Red, 91 bytes

```
func[a][i: last sort copy a until[forall a[prin either a/1 = i[1][sp]]print""0 > i: i - 1]]

```

Try it online!

-6 bytes from Galen Ivanov.

# Answer
> 6 votes
# Jelly, 7 bytes

```
Ṭ€z0Ṛo⁶

```

Try it online!

Outputs a list of lines. +1 byte (append `Y`) if unacceptable.

Takes input 1 indexed, uses `1` as the mountain character

## How it works

```
Ṭ€z0Ṛo⁶ - Main link. Takes a list L on the left
 €      - Over each element in L:
Ṭ       -   Untruthy; Map each n to [0, 0, ..., 1] with n-1 zeros
  z0    - Transpose, padding with zeros
    Ṛ   - Reverse
     o⁶ - Replace 0s with spaces

```

# Answer
> 6 votes
# , 17 bytes

```
[:|.@|:' x'#~,.&1

```

Try it online!

+6 thanks to Lynn for spotting a bug in the original solution: `' x'{~=\:~.` This approach can be made to work but it's no longer golfy: `' x'{~]=/~[:i.1-@+>./`

## how

* `,.&1` Zip input with 1:

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

```
* `' x'#~` Duplicate `' x'` according to these pairs

```
 x
x
x
 x
  x
    x
  x
x

```
* `[:|.@|:` Rotate left:

```
     x

    x x
x  x
 xx    x

```

# Answer
> 6 votes
# Jelly, 6 bytes

```
=ⱮṀṚo⁶

```

A monadic Link that accepts a list of positive integers (the 1-indexed option) and yields a list of lists of characters and integers (`1` being the choice for `x`).

**Try it online!** (The footer joins with newlines and then Jelly's implicit, smashing print produces the output.)

### How?

```
=ⱮṀṚo⁶ - Link: list of integer heights, H
  Ṁ    - maximum (H) -> M
 Ɱ     - map across (h in [1..M]) with:
=      -   (H) equals (h) (vectorises)
   Ṛ   - reverse -> X
     ⁶ - space character
    o  - (X) logical OR (' ') (vectorises)

```

# Answer
> 4 votes
# Charcoal, 6 bytes

```
↑ＥＡ◧xι

```

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

```
  Ａ     Input array
 Ｅ      Map over elements
    x   Literal string `x`
   ◧    Left-padded to width
     ι  Current element
↑       Print rotated

```

# Answer
> 4 votes
# Japt `-R`, 7 bytes

1-indexed, using `"` for the peaks.

```
£QùXÃÕÔ

```

Try it

```
£QùXÃÕÔ     :Implicit input of array
£           :Map each X
 Q          :  Quotation mark
  ùX        :  Left pad with spaces to length X
    Ã       :End map
     Õ      :Transpose
      Ô     :Reverse
            :Implicit output joined with newlines

```

# Answer
> 4 votes
# Ruby, 51 bytes

```
->a{(-a.max..0).map{|y|a.map{|x|x==-y ??x:' '}*''}}

```

Try it online!

# Answer
> 4 votes
# Python 3, 67 bytes

```
lambda x:[[v==i and'*'or' 'for v in x]for i in range(max(x),-1,-1)]

```

Try it online!

`for i in range(max(x),-1,-1)` -\> identify how high the mountain will be, max value is first line (top), so start from max, iterate to 0

`[v==i and'*' or' ' for v in x]` -\> for every integer in input set it as * if height matches current line, set it whitespace otherwise.

\[EDIT\] as per @hyper-neutrino suggestion to get 3 bytes less, and wrapped in lambda as per @Razetime comment

# Answer
> 3 votes
# Vyxal, ~~11~~ 9 bytes

-2 bytes through auto-vectorizing

```
ð*×+ðÞṪṘ⁋

```

```
ð*            # vectorised n spaces
  ×+          # append "*"
     ðÞṪ      # transpose with space as filler
        Ṙ⁋    # reverse and join by newline

```

Try it Online!

# Answer
> 3 votes
# JavaScript (Node.js), ~~77~~ ~~74~~ ~~73~~ 70 bytes

-1 thanks to @RecursiveCo.
-3 thanks to @m90's idea

```
a=>{for(i=Math.max(...a);i;i--)console.log(a.map(e=>i^e&&' ').join``)}

```

Try it online!

Takes one-indexed input.

# Answer
> 3 votes
# , 65 bytes

```
function(a)for(i in max(a):0)cat(c(' ','x')[1+(a==i)],'
',sep='')

```

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), 44 bytes

```
Print@@@Table[" "Unitize[#+i],{i,-Max@#,0}]&

```

Try it online!

Prints the mountain, using `0` instead of `x`.

Remove the `Print@@@` for -8 bytes if an array of characters and numbers is acceptable output.

# Answer
> 2 votes
# Octave / MATLAB, 43 bytes

```
@(x)flip([accumarray([x find(x)],3)+32 ''])

```

Anonymous function that inputs a 1-based column vector and outputs a char matrix with `#` and

**Try it online!**

# Answer
> 2 votes
# Pip `-l`, 10 bytes

```
R:sXg.0ZDs

```

Takes the integers as command-line arguments. Outputs using `0` in place of `x`. Try it here! Or, here's an 11-byte equivalent in Pip Classic: Try it online!

### Explanation

```
            g is list of cmdline args; s is space (implicit)
  sXg       Convert each arg to a string of that many spaces
     .0     Append 0 to each string of spaces
       ZDs  Transpose, extending shorter strings with a default value of space
R:          Reverse the resulting list
            Autoprint, one row per line (-l flag)

```

# Answer
> 2 votes
# Canvas, 7 bytes

```
｛ ×x＋］↶

```

Try it here!

# Answer
> 2 votes
# Pyth, 7 bytes

```
_.tm+*;

```

Try it here!

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


title: How long does it take to paint a stick?

text:
# Question
Title: How long does it take to paint a stick?
(Based on this Math.SE problem, which also provides some graphics)

I have a stick which looks kinda like this:

I want it to look kinda like this:

I'm not an expert painter, however, so before I start such an ambitious DIY project, I want to make sure that I'm not in over my head.

Your program should tell me how how many steps are involved in painting this stick. Each step involves painting a continuous area with a solid color, which covers up previous layers of paint. For the above example, I could paint the left half blue, the right half red, and then the two separate green areas for a total of 4 steps (the green is not continuously painted).

Here it is in ASCII:

```
------
bbb---
bbbrrr
bgbrrr
bgbrgr

```

There are a couple different ways to paint this stick and end up with the same result. I'm only interested in the time estimate, however, which is four steps.

## Goal

Your program should output the minimum number of steps needed to paint a stick with a given color scheme. The paint scheme will be in the form of a string of characters, while output will be a number. This is code golf. Shortest program wins.

## Input

Your program will receive the coloring scheme for a stick in the form of a string of letters. Each unique letter (case sensitive) represents a unique color.

```
YRYGR

grG

GyRyGyG

pbgbrgrp

hyghgy

```

## Output

These numbers are the least number of steps needed to paint the sticks.

```
4

3

4

5

4

```

## Explanations

This is how I arrived at the above numbers. Your program does not need to output this:

```
 -----
 YYY--
 YRY--
 YRYG-
 YRYGR

 ---
 g--
 gr-
 grG

 -------
 GGGGGGG
 GyyyGGG
 GyRyGGG
 GyRyGyG

 --------
 pppppppp
 pbbbpppp
 pbbbrrrp
 pbgbrrrp
 pbgbrgrp

 ------
 -yyyyy
 -ygggy
 hygggy
 hyghgy

```

Edit: I'll add more test cases if they prove to be more difficult test cases.

# Answer
# Python 3, ~~60~~ 59 bytes

```
p=lambda s:len(s)and-~min(sum(map(p,s.split(c)))for c in s)

```

Try it online!

Ungolfed:

```
def paint(stick):
    if not stick:
        return 0
    return 1 + min(
        sum(paint(part) for part in stick.split(c))
        for c in stick
    )

```
> 8 votes

# Answer
### GolfScript, 82 72 67 characters

```
.,n*{:c,,{[).2$1<*\c>+1$.,,{).2$<\3$<=},,.@>@@>]}%\;{~S)}%$0+0=}:S~

```

Reasonably fast for a GolfScript program, examples:

```
> hyghgy
4

> pbgbrgrp
5

```

The algorithm used works through the colors left-to-right recursively, according to the following statements:

* Ignore all parts from the left which already have the required color. Overpainting them again will not provide a better answer.
* If the complete stick already has the desired color, return 0 steps as result.
* Otherwise, take the target color of the now leftmost part (i.e. the first not in the desired color).

+ Paint 1 part with the target color and recurse.
    + Paint 2 parts with this color and recurse.

...

+ Paint the whole remaining stick with this color and recurse.

Take the minimum of all those numbers and add 1 (for the current step). Return this as the optimal number of steps.

This algorithm works, because the leftmost part has to be painted at one time anyways, so why not do it immediately - in any possible fashion.

```
.,n*         # prepare the initial situation (target stick, unpainted stick)
             # used n instead of '-' for the unpainted parts, because it is shorter
{            # Define the operator S which does t c S -> n
             #   - t: the desired target colors
             #   - c: the stick as it is colored currently
             #   - n: minimum number of steps required to go from c to t
  :c         # Assign the current configuration to the variable c
  ,,{[       # Map the list [0 1 2 .. L-1]
             # We will build a list of all possible configurations if we paint
             # the stick with the 0th part's color (either 1 or 2 or 3 or ... parts)
    ).       # Increase the number, i.e. we paint 1, 2, 3, ... L parts, copy
    2$1<     # Take the first color of the target configuration
    *        # ...paint as many parts
    \c>+     # ...and keep the rest as with the current stick
    1$       # take the target configuration
             # Top of stack now e.g. reads
             #    h----- hyghgy (for i=0)
             #    hh---- hyghgy (for i=1)
             # Next, we strip the common leading characters from both strings:
    .,,      # Make list [0 1 2 ... L-1]
    {        # Filter {}, all the numbers for which the first j+1 parts are the same
      ).     # incr j
      2$<    # take leftmost j parts of stick A
      \3$<   # take leftmost j parts of stick B
      =      # are they equal?
    },,      # The length of the result is the number of common parts.
    .@>      # cut parts from A
    @@>      # cut parts from B
  ]}%
  \;         # Remove the target from the stack (not needed anymore)
             # We now have a list of possible paintings where 1, 2, ..., L parts were
             # painted from the left with the same color.
             # All configurations were reduced by the common parts (they won't be
             # painted over anyways)
  {~S)}%     # Call the method S recursively on the previously prepared configurations
  $0+0=      # $0= -> sort and take first, i.e. take the minimum, 0+ is a workaround
             # if the list was empty (i.e. the operator was called with a stick of length 0).
}:S
~            # Execute S

```
> 3 votes

# Answer
**JavaScript: 187 Bytes**

Assuming we're allowed to just have the input and output to a function (please)!

```
function p(w){var j,l,s=-1,i,m=i=w.length;if(m<2)return m;for(;i--;){l = 1;for(var k=-1;(j=k)!=m;){if((k=w.indexOf(w[i],++j))==-1)k=m;l+=p(w.substring(j,k));}if(s==-1||l<s)s=l;}return s;}

```

**157 Bytes** by doing further ugly optimization (Which is part of the point, and I found incredibly fun):

```
function p(w){var j,l,s=-1,i,m=i=w.length;if(m<2)return m;for(;i--;s<0|l<s?s=l:1)for(l=1,j=0;~j;)l+=p(w.substring(j,(j=w.indexOf(w[i],j))<0?m:j++));return s}

```

**135 Bytes** I realised that the length of the input is an upper bound and I don't need to handle trivial cases separately now.

```
function p(w){var j,l,s,i,m=s=i=w.length;for(;i--;l<s?s=l:1)for(l=1,j=0;~j;)l+=p(w.substring(j,~(j=w.indexOf(w[i],j))?j++:m));return s}

```

Test cases:

```
p("YRYGR")
4
p("grG")
3
p("GyRyGyG")
4
p("pbgbrgrp")
5
p("hyghgy")
4

```

Expanded version:

```
function paint(word) {
    var smallest = -1;
    if(word.length < 2) return word.length;
    for(var i = word.length; i-->0;) {
        var length = 1;
        for(var left, right = -1;(left = right) != m;) {
            if((right = word.indexOf(word[i],++left)) == -1) right = word.length;
            if(left != right) length += paint(word.substring(left , right));
        }
        if(smallest == -1 || length < smallest) smallest = l;
    }
    return smallest;
}

```

For every character of the input, calculate the length of the pattern if we paint that colour first. This is done by pretending we paint that colour and then making sub sections out of the bits that aren't that colour, and recursively calling the paint method on them. The shortest path is returned.

Example (`YRYGR`):

Initially, try `R`. This gives us the sub groups `Y` and `YG`. `Y` is trivially painted in one go.

For `YG`: Try `G`, `Y` is trivial, length `2`. Try `Y`, `G` is trivial, length 2. `YG` is therefore length `2`.

Painting `R` first therefore gives us `1 + 1 + 2 = 4`

Then try `G`. This gives us the sub groups `YRY` and `R`. `R` is trivial.

For `YRY`:

Try `Y`: `R` is trivial, length `2`. Try `R`: `Y` and `Y` are the two groups, length `3`.

`YRY` is length `2`.

Painting `G` first gives `1 + 1 + 2 = 4`

Then try `Y`. This gives the sub groups `R` and `GR`. `R` trivial, `GR` is length `2`. `Y` is length `4`

This implementation would then check R and Y again to reduce code length. The result for `YRYGR` is therefore `4`.
> 2 votes

# Answer
## CoffeeScript - 183 247 224 215 207

```
x=(s,c='')->return 0if !s[0]?;return x s[1..],c if s[0]is c;l=s.length;return x s[1...l],c if s[l-1]is c;i=s.lastIndexOf s[0];1+(x s[1...i],s[0])+x s[i+1..],c
y=(z)->z=z.split "";Math.min (x z),x z.reverse()

```

Demo on JSFiddle.net

Ungolfed version including debug code and comments:

```
paintSubstring = (substring, color = '####') ->
  console.log 'Substring and color', substring, color, substring[0]
  # no need to color here
  if !substring[0]?
    return 0
  # no need to recolor the first part
  if substring[0] is color
    return paintSubstring (substring[1..]), color
  l = substring.length
  # no need to recolor the last part
  if substring[l-1] is color
    return paintSubstring substring[0...l], color
  # cover as much as possible
  index = substring.lastIndexOf substring[0]
  part1 = substring[1...index]
  part2 = substring[index+1..]
  console.log 'Part 1:', part1
  console.log 'Part 2:', part2
  # color the rest of the first half
  p1 = paintSubstring part1, substring[0]
  # color the rest of the second half, note that the color did not change!
  p2 = paintSubstring part2, color
  # sum up the cost of the substick + this color action
  return p1+p2+1
paintSubstringX=(x)->Math.min (paintSubstring x.split("")), paintSubstring x.split("").reverse()
console.clear()
input = """YRYGR
grG
GyRyGyG
pbgbrgrp
aaaaaaaa
hyghgy""".split /\n/
for stick in input
  console.log paintSubstringX stick

```
> 1 votes

# Answer
## Python, 149 chars

```
D=lambda s:0 if s=='?'*len(s)else min(1+D(s[:i]+'?'*(j-i)+s[j:])for i in range(len(s))for j in range(i+1,len(s)+1)if set(s[i:j])-set('?')==set(s[i]))

```

I use `?` to mark an area that may be any color. `D` picks a contiguous region of the stick that contains only a single color (plus maybe some `?`s), colors that region last, replaces that region with `?`s, and recurses to find all the previous steps.

Exponential running time. Just barely fast enough to do the examples in a reasonable time (a few minutes). I bet with memoization it could be much faster.
> 1 votes

# Answer
## Python 3 - 122

```
def r(s,a):c=s[0];z=c in a;return s[1:]and min([1+r(s[1:],a+c)]+[r(s[1:],a[:a.rfind(c)+1])]*z)or(1-z)
print(r(input(),''))

```

It seems to work, but I'm still not 100% sure that this method will always find the minimum number of steps.
> 1 votes

# Answer
## Haskell, ~~118~~ 86 characters

```
p""=0
p(a:s)=1+minimum(map(sum.map p.words)$sequence$map(a%)s)
a%b|a==b=b:" "|1<3=[b]

```

Test runs:

```
λ: p "YRYGR"
4

λ: p "grG"
3

λ: p "GyRyGyG"
4

λ: p "pbgbrgrp"
5

λ: p "hyghgy"
4

λ: p "abcacba"
4

```

This method isn't even all that inefficient!
> 1 votes

# Answer
Haskell, 143 chars

```
f s=g(r n ' ')0where{r=replicate;n=length s;g p l=minimum$n:[0|p==s]++[1+g(take i p++r(j-i)(s!!i)++drop j p)(l+1)|l<n,i<-[0..n-1],j<-[i+1..n]]}

```

This tries all possible rewritings up to the length of the string, and goes until it finds one that constructs the input pattern. Needless to say, exponential time (and then some).
> 0 votes

# Answer
A simple breadth first search. It doesn't put anything on the queue that's already been seen. It works in under a second for all of the examples but 'pbgbrgrp' which actually takes a full minute :(

Now that I have something that *works* I'll be working on finding something faster and shorter.

**Python - ~~300~~ 296**

```
def f(c):
 k=len(c);q=['0'*99];m={};m[q[0]]=1
 while q:
  u=q.pop(0)
  for x in ['0'*j+h*i+'0'*(k-j-i) for h in set(c) for j in range(1+k) for i in range(1,1+k-j)]:
   n=''.join([r if r!='0' else l for l,r in zip(u,x)])
   if n == c:
     return m[u]
   if not n in m:
    m[n]=m[u]+1;q.append(n)

```
> 0 votes

---
Tags: code-golf, math
---


title: Reverse a 1-dimensional array

text:
# Question
Title: Reverse a 1-dimensional array
*Note: This challenge is not the same.*

# Challenge

Believe it or not, we haven't got ONE challenge for reversing one-dimensional arrays (although we've got one for n-dimensional ones)! This should operate only on the 1st dimension, not on all dimensions of an array.

# Rules

* Standard loopholes are **denied**
* **`[[1, 2], [3, 4]]`** becomes **`[[3, 4], [1, 2]]`**, not **`[[4, 3], [2, 1]]`**.
* This is , but no answer is accepted. Go beat the others!
* You can get the array any way, except hardcoding. You can also get a string and process it.
* The input will be an array (yes, commas or no commas, it needs to be an array).

# Test cases

These are the test cases:

```
[1, 2, 3, 4]
[1, 2, 'hello', 'world!']
[[1, 2, 3, 4], [2, 3, 4, 1]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

```

These are the supposed results:

```
[4, 3, 2, 1]
['world!', 'hello', 2, 1]
[[2, 3, 4, 1], [1, 2, 3, 4]]
[23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

```

You may accept input as `[1 2 3 4]`, or even `1 2 3 4`, or any other form or array your language has.

# Answer
> 13 votes
# Jelly, 1 byte

Try it online! It reverses an array. <sub>(yay this is my first Jelly answer!)</sub>

# Answer
> 12 votes
# Pyth, ~~2~~ 1 byte~~s~~

*1 byte off thanks to Doorknob*

```
_

```

`_` is reverse, and Pyth takes implicit input. Yes, my first Pyth answer is an underscore.

# Answer
> 6 votes
# Python 2, 8 bytes

```
reversed

```

This is too short.

# Answer
> 6 votes
# , 3 bytes

Literally reverses array. Implicitly performs I/O.

# Answer
> 4 votes
# Python 3, 16 bytes

```
lambda x:x[::-1]

```

This isn't even enough characters to post as an answer.

# Answer
> 4 votes
# C, 65 bytes

Takes a pointer to the start of the list and a list length.

```
void f(int*a,int s){int t=*a;*a=a[--s];a[s--]=t;if(s>1)f(a+1,s);}

```

This is a recursive algorithm that swaps the first element with the last, and then runs the same function on the middle.

Ungolfed:

```
void f(int* a, int s){
  int t = a[0];
  a[0] = a[--s];
  a[s--] = t;
  if(s > 1){
    f(a + 1, s - 2);
  }
}

```

# Answer
> 3 votes
# Python 2, 19 bytes

```
print input()[::-1]

```

# Answer
> 3 votes
# 05AB1E, 1 byte

Code:

```
R

```

Try it online!.

# Answer
> 3 votes
# Brachylog, 2 bytes

```
r.

```

which expects a list as Input and unifies the reverse with the Output.

### Alternative

```
rw

```

which expects a list as Input and writes the reverse to `STDOUT`.

# Answer
> 3 votes
# Java 8, ~~62~~ ~~38~~ 30 bytes

```
java.util.Collections::reverse

```

Modifies the input-`ArrayList` instead of returning a new one to save bytes.

-8 bytes thanks to *@OliverGrégoire*.

Try it here.

---

With an array as input instead of `ArrayList` (**62 bytes)**:

```
import java.util.*;a->{Collections.reverse(Arrays.asList(a));}

```

Modifies the input-array instead of returning a new one to save bytes.

Try it here.

---

Looping over the array to reverse it would be **~~75~~ 69 bytes** instead:

```
a->{Object t;for(int i=0,j=a.length;i<--j;a[i++]=a[j],a[j]=t)t=a[i];}

```

Try it here.

-5 bytes thanks to *@OliverGrégoire*.

# Answer
> 2 votes
# Ruby, 14 bytes

you can't get simpler than this:

```
->a{a.reverse}

```

# Answer
> 2 votes
# JavaScript ES6, 14 bytes

```
x=>x.reverse()

```

Simple enough. Anonymous lambda that reverses an array.

# Answer
> 2 votes
## Actually, 1 byte

```
R

```

`R`everses the input list. These are words to make this answer long enough.

# Answer
> 2 votes
# SmileBASIC, 34 bytes

```
DEF R A
DIM T[LEN(A)]RSORT T,A
END

```

`RSORT` actually just sorts the arrays, and then reverses them.

### Cheating answer: (requires turning the screen upside down):

```
LINPUT S$ATTR 2?S$

```

# Answer
> 2 votes
# Python 3, 12 bytes

```
list.reverse

```

Surprised nobody else used this. Reverses in place, but I don't think there are any restrictions on that.

# Answer
> 1 votes
# Jolf, 1 + 1 = 2 bytes

```
_

```

Try it here! (bonus for polyglot with Pyth?) `_` reverses (negates) an array. (Make sure pretty output is on.)

# Answer
> 1 votes
## Pyke, 1 byte

```
_

```

Try it here!

Pyke has implicit input and output. Polyglot with Pyth, Jolf,

# Answer
> 1 votes
# Perl 5, 11 bytes

A subroutine:

```
{reverse@_}

```

# Answer
> 1 votes
# Keg, 1 byte

Nothing interesting. Keg has a built-in. (Since Keg does not have any other means of representing an array, let's assume the stack is the array (and in fact it is).)

```
?

```

Try it online!

# Answer
> 0 votes
# Python, 16 bytes

```
lambda l:l[::-1]

```

*Please examine this answer again. I was a bit lazy answering this :P*

Thanks to 55749 (J843136028) for suggesting to convert this to a function :)

# Answer
> 0 votes
# Molecule, 8 bytes

```
I"Ar"+`n

```

Explanation:

```
I"Ar"+`n
I"Ar"    Read input, append the command (reverse array) as a string.
     +   concatenate the 2 strings
      `n set the program's source code to that new string.

```

Simple I/O:

```
Input    | Output
[5 "n"]    [n 5.0]
['n 3]     [3.0 n]

```

# Answer
> 0 votes
## Lua, 61 bytes

It beats C! \o/

It simply fill a new table in the reversed order.

```
function f(g)h={}for i=0,#g do h[#g-i]=g[i+1]end return h end

```

It could have been done by working on the pointer, suppressing the return statement and the new table definition, but it actually is longer by 2 bytes

```
function f(g)for i=1,#g/2 do x=#g-i+1g[x],g[i]=g[i],g[x]end end

```

# Answer
> 0 votes
# MySQL, 64 bytes

```
set@=1;select a from(select a,@:=@+1 n from t order by n desc)u;

```

Tested on 5.6.24.

My first SQL answer; please provide feedback!

# Answer
> 0 votes
# PHP, 17 bytes

```
$r=array_reverse;

```

call `$r($array)`

non-built-in version, 53 bytes:

```
function r($a){while($a)$b[]=array_pop($a);return$b;}

```

call `r($array)`

generator for PHP \>= 5.5, 45 bytes

```
function y($a){while($a)yield array_pop($a);}

```

usage: `foreach(y($array)as$v)var_dump($v);`

# Answer
> 0 votes
# TI-Basic, 16 bytes

```
seq(Ans(I),I,dim(Ans),1,~1

```

No built-ins for reversing an array in TI-Basic...

# Answer
> 0 votes
# Triangularity, 7 bytes

```
.).
IER

```

Try it online!

# Answer
> 0 votes
# Dodos, 43 bytes

```
	main dab
	dab - a
-
	- dip
a
	dot dab
	dot

```

Try it online!

(the `-` function subtracts and `a` is `lambda x: [sum(x[1:]), sum(x)]`. So `dab - a` takes the first element of a list)

# Answer
> 0 votes
# Preproc, 279 bytes

```
#define v(x)Z(Z(Z(Z(Z(x)))))
#define Z(x)Y(Y(Y(Y(Y(x)))))
#define Y(x)X(X(X(X(X(x)))))
#define X(x)e(e(e(e(e(x)))))
#define e(x,...)x
#define d()
#define s(x,y,...)y
#define r(x,y...)i(x,,R d d d d()()()()()(y)x)
#define C,
#define R()r
#define i(x,v...)s d()(C##x v)
v(r e()(I))

```

Try it online!

---

Some notes.

* Because the language (one pass of the C preprocessor) is not Turing-complete (as far as I know), this can only process arrays up to a fixed size. That can be increased by making `v(x)` evaluate `e(x)` more times.
* Input on command line, separated with `,` (please only give non-negative integers)
* Output on stdout, separated with spaces.
* My first Preproc answer. Golfing suggestions are appreciated.
* I would appreciate it if someone explain why do I need 4 nested `d`.

# Answer
> 0 votes
# MathGolf, 1 byte

Nothing interesting. MathGolf has a built-in.

```
x

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Unicode), 1 byte

This works both on lists of lists and proper multi-dimensional arrays.

Try it online!

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


title: Output the Partial Products

text:
# Question
Title: Output the Partial Products
In long multiplication, after multiplying the numbers, you are left with the partial products, in this challenge you will output those partial products.

Because long multiplication is long, to compensate your code will need to be as short as possible.

## Examples

```
34, 53
102, 1700

48, 38
384, 1440

361, 674
1444, 25270, 216600

0, 0
0

1, 8
8

```

## Specifications

* Input / Output may be in any reasonable format such as array, comma-separated string (or any other delimiter that's not a digit), list, function arguments, etc.
* Partial products must be in increasing order.
* If a partial product is `0`, you can choose whether you want to output it or not.

---

This is so shortest code in bytes wins!

# Answer
# Jelly, 10 bytes

```
DU×µLR’⁵*×

```

Try it online!

### How it works

```
DU×µLR’⁵*×  Left argument: multiplier -- Right argument: multiplicant

D           Convert the multiplier to base 10 (array of digits).
 U          Reverse the array.
  ×         Multiply each digit by the multiplicant.
   µ        Begin a new, monadic chain. Argument: A(array of products)
    L       Get the length of A.
     R      Turn length l into [1, ..., l].
      ’     Decrement to yield [0, ..., l-1].
       ⁵*   Compute 10**i for each i in that range.
         ×  Hook; multiply the powers of ten by the corresponding elements of A.

```
> 4 votes

# Answer
# Pyth, 12 bytes

```
.e**Qsb^Tk_w

```

Test suite

Takes input newline separated, e.g.

```
361
674

```

**Explanation:**

```
.e**Qsb^Tk_w
                Implicit: Q = eval(input()),T = 10
           w    Input the second number as a string.
          _     Reverse it.
.e              Enumerated map, where b is the character and k is the index.
     sb         Convert the character to an int.
   *Q           Multiply by Q.
  *    ^Tk      Multiply by T ^ k. (10 ^ index)

```
> 7 votes

# Answer
# JavaScript (ES7), 48 bytes

```
(a,b)=>[...b+""].reverse().map((d,i)=>10**i*a*d)

```

### ES6 (56 bytes)

```
(a,b)=>[...b+""].reverse().map((d,i)=>a*d+"0".repeat(i))

```

## Explanation

Returns an array of partial products as numbers.

```
(a,b)=>
  [...b+""]    // convert the multiplier to an array of digits
  .reverse()   // reverse the digits of the multiplier so the output is in the right order
  .map((d,i)=> // for each digit d of the multiplier
    10**i      // get the power of ten of the digit
      *a*d     // raise the product of the digit to it
  )

```

## Test

Test uses `Math.pow` instead of `**` to make it work in standard browsers.

```
var solution = (a,b)=>[...b+""].reverse().map((d,i)=>Math.pow(10,i)*a*d)
```

```
A = <input type="text" id="A" value="361" /><br />
B = <input type="text" id="B" value="674" /><br />
<button onclick="result.textContent=solution(+A.value,+B.value)">Go</button>
<pre id="result"></pre>
```
> 4 votes

# Answer
# Lua, ~~72~~ 68 Bytes

```
b=arg[2]:reverse()for i=1,#b do print(arg[1]*b:sub(i,i)*10^(i-1))end

```
> 3 votes

# Answer
# APL, 21 bytes

```
{⍺×x×10*1-⍨⍳≢x←⊖⍎¨⍕⍵}

```

This is a dyadic function that accepts integers on the left and right and returns an array. To call it, assign it to a variable.

Explanation:

```
             x←⊖⍎¨⍕⍵} ⍝ Define x to be the reversed digits of the right input
     10*1-⍨⍳≢         ⍝ Generate all 10^(1-i) for i from 1 to the number of digits
{⍺×x×                 ⍝ Multiply the right input by the digits and the powers of 10

```
> 3 votes

# Answer
# Pyth, 26 bytes

```
DcGHKjHTFNJlK*G*@Kt-JN^TN

```

This defines a function `c` such that it accepts `2` arguments, and the function prints the partial products.

```
DcGHKjHTFNJlK*G*@Kt-JN^TN
DCGH                      Define function c(G, H)
    KjHT                  Set K to the list of digits converting H to base 10
        FNJlK             Set J to the length of K and loop with variable N
                          (Implicit: print)
             *G*@Kt-JN    Calculates the partial product
                      ^TN Raising it to the appropriate power of 10

```
> 2 votes

# Answer
# 05AB1E, 15 bytes

Code:

```
VDgUSXFTNmY**=\

```

Explanation:

```
VDgUSXFTNmY**=\

V                 # Assign the input to Y
 D                # Duplicate of input, because the stack is empty
  g               # Pushes the length of the last item
   U              # Assign the length to X
    S             # Split the last item
     X            # Pushes X (length of the last item)
      F           # Creates a for loop: for N in range(0, X)
       TNm        # Pushes 10 ^ N
          Y       # Pushes Y (first input)
           *      # Multiplies the last two items
            *     # Multiplies the last two items
             =    # Output the last item
              \   # Discard the last item

```
> 2 votes

# Answer
# MATL, 18 bytes

```
ij48-tn:1-P10w^**P

```

The compiler (5.1.0) works in Matlab and in Octave.

Each number is input on a separate line.

### Example

```
>> matl ij48-tn:1-P10w^**P
> 361
> 674
1444  25270 216600

```

### Explanation

```
i           % input first number (say 361)
j           % input second number, interpreted as a string (say '674')
48-         % subtract '0' to obtain vector of figures (gives [6 7 4])
tn:1-P      % vector [n-1, ... 1, 0] where n is the number of figures (gives [2 1 0])
10w^        % 10 raised to that, element-wise (gives [100 10 1])
*           % multiply, element-wise (gives [600 70 4])
*           % multiply (gives 361*[600 70 4], or [216600 25270 1444])
P           % flip vector ([1444 25270 216600]). Implicitly display

```
> 1 votes

# Answer
## Haskell, ~~60~~ ~~57~~ 54 bytes

```
g x=zipWith(\b->(x*10^b*).read.pure)[0..].reverse.show

```

5 bytes less (drop the `.show`) if I can take the second number as a string.

Usage example: `g 361 674` -\> `[1444,25270,216600]`.

Multiply every digit of the reverse of `y` with `x` and scale with `10^i` where `i = 0,1,2,...`.

Edit: Thanks to @Mauris for 3 bytes!
> 1 votes

# Answer
# Julia, ~~50~~ 49 bytes

```
f(a,b)=[a*d*10^~-i for(i,d)=enumerate(digits(b))]

```

This is a function that accepts two integers and returns an integer array.

The `digits` function returns an array of the input integer's digits in reverse order. We get the index, value pairs using `enumerate` and compute the partial products as the first input times the digits times 10 raised to the power of the digit's index - 1.

Saved a byte thanks to Dennis!
> 1 votes

# Answer
# CJam, ~~19~~ 17 bytes

```
q~W%eef{~~A@#**}p

```

Takes input with the first item being an integer and the second a string (e.g. `34 "53"`). Suggestions are welcome, as I'm sure it can be shorter. Thanks to Dennis for saving two bytes.

Try it online.

### Explanation

```
q~    e# Get input and evaluate it, x and "y"
W%    e# Reverse y so it will be properly sorted
ee    e# Enumerate through y with each character and its index
f{    e# For each digit in y...
  ~~  e# Convert the digit to an integer on the stack
  A@# e# Take 10 to the power of y's index
  **  e# Multiply all three together to get the final result
}
p     e# Print the array

```
> 1 votes

# Answer
# Python 2, 61

```
def p(a,b):
 j=0
 while b>0:
  print`b%10*a`+j*'0';b/=10;j+=1

```
> 1 votes

# Answer
## Haskell, 37 bytes

```
a%0=[]
a%b=b`mod`10*a:(a*10)%div b 10

```

No stringifying, just arithmetic. Recursively prepends the smallest partial product to the rest, where the last digit of `b` is truncated and a multiplier of 10 is applied. The operator precedence works nicely.
> 1 votes

# Answer
# Japt, 8 bytes

Takes input in reverse order with the first being a digit array and the second being an integer. If both inputs *must* be of the same type then we can take them both as strings and add `¬` to the beginning.

```
ÔË*V*ApE

```

Try it

```
¬ÔË*V*ApE     :Implicit input of array U & integer V (or strings U & V)
¬             :(Split U, if inputs are strings)
 Ô            :Reverse U
  Ë           :Map each element at 0-based index E
   *V*        :  Multiply by V multiplied by
      A       :  10
       pE     :  Raised to the power of E (1eE would also work in place of ApE)

```
> 1 votes

# Answer
# , 11 chars / 23 bytes (non-competitive)

```
ᴙíⓢⓜî*$*Ⅹⁿ_

```

`Try it here (Firefox only).`

Found a bug while coding the solution to this problem...

# Explanation

```
          // Implicit: î = input 1, í = input 2
ᴙíⓢ      // reverse í and split it into an array
ⓜî*$*Ⅹⁿ_ // multiply î by each individual digit in í and put in previous array
          // implicit output

```
> 0 votes

# Answer
## Japt, 28 bytes

```
I=[]Vs w m@IpApY+1 /A*U*X};I

```

Explanation:

```
I=[]Vs w m@IpApY+1 /A*U*X};I
I=[]                         //that's simple, init an array I
    Vs                       //take the second input and convert to string
       w                     //reverse it and...
         m@              }   //...map through the chars; X is a char, Y is counter
           Ip............    //push the following value into I...
             ApY+1 /A*U*X    //10^(Y+1)/10*U*X, U is the first input
                           I //output the resulting array

```
> 0 votes

# Answer
## Python 2, 42 bytes

```
f=lambda a,b:b*[0]and[b%10*a]+f(a*10,b/10)

```

No stringifying, just arithmetic. Recursively appends the smallest partial product to the rest, where the last digit of `b` is truncated and a multiplier of 10 is applied.
> 0 votes

# Answer
# Husk, 10 bytes

```
z*:1İ⁰↔M*d

```

Try it online!
> 0 votes

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


title: The Great Betting Game

text:
# Question
Title: The Great Betting Game
Your task is to create either a console "app" or a function which allows the user to bet on certain numbers or retire / claim rounds.

---

## Bets

Your program or function will prompt for a command after an action, and the bet is the most important, crucial to the operation of the app.

A bet looks something like this:

```
bet 5
bet 4 9

```

Each time the user bets, your application should choose a 1-digit number (1-9, not including zeroes) at random. It is reasonable to assume that your pseudo-random number generator is uniformly random.

When your application receives a `bet` command, there may be 1 or 2 numbers after `bet`. They will be 1-digit numbers from 1-9.

If there is 1 number, that means that the user is willing to bet on a single number in the range `1-9` coming out.

If there are 2 numbers, things get slightly more complicated. This means the user is instead betting on a *range*: with bounds included. So `bet 4 9` means the user is betting on a number in the range `4-9` being selected.

The first time you bet in a "round" (explained later), you win 1$ if your number is selected, but lose 2$ if your number is not selected.

However, if the user bets on a range (which has a higher chance of winning), the money won is less: the first bet in a round wins `1 - (rangeEnd - rangeBegin + 1) / 10` while losing that bet will deduct double that amount from the player's balance.

Each subsequent bet doubles the "stake". The second bet in a round wins 2$ for one number and `2 - 2 (rangeEnd - rangeBegin + 1) / 10` for a range, and losses are worth double each. Then the third bet wins 4$ for one number, `4 - 4 (rangeEnd - rangeBegin + 1) / 10` for a range, etc.

After a bet, some output should occur: an indication of the result as well as the chosen number (`chosen <number>`) If the bet is won, something like

```
won 1 chosen 5

```

should be output. If the bet is lost, then something like

```
lost 2 chosen 7

```

## Retirement

At any point, the user is also allowed to "retire" the current round if he or she is too afraid to lose money. This adds the player's current money to the main balance, which is initially set to zero. This also triggers a new round in which the first bet wins 1$, second 2$, etc with the above rules for ranges also applying. The command is simply

```
retire

```

This produces no output.

## Claims

When the player decides to leave the "casino", he or she must "claim" the money, which in the context of your app must output the player's balance and **halt**. No commands should be accepted after `claim`.

Command:

```
claim

```

## Example

This is a console app. Rules for functions and other general info are provided below.

Note that `>`  before commands are not necessary. They are just shown here for clarity.

Also note that the numbers here were chosen by me and not an RNG, but that your code is expected to produce the numbers non-deterministically.

```
> bet 6
lost 2 chosen 3
> bet 3 7
won 1 chosen 6
> bet 9
won 4 chosen 9
> retire
> bet 1
lost 2 chosen 6
> claim
1

```

In the second bet of round 1, the range was 3-7, so the player won `2 - 2 (7 - 3 + 1) / 10 = 2 - 2 (5/10) = 2 - 1 = 1` dollars.

## Rules for functions

Functions are allowed, but they have a different I/O format.

Input can be taken as a newline-separated string of commands, an array/list of commands, etc. Nothing new there. The commands can be taken as sub-lists too, so `bet 4 9` can become `['bet', 4, 9]` in JavaScript, for instance, and `retire` could be `['retire']`.

Return value can be any of: newline-separated string of outputs, array/list of outputs, etc. Post-bet output can be a list of numbers (`-2 4` for `lost 2 chosen 4` and `64 9` for `won 64 chosen 9`), and you will have to output floating point numbers from time to time.

As @Arnauld pointed out in the comments, your function might not necessarily be **reusable** (see here).

## Other rules

Invalid input will never be given. So no ranges where the end is less than or equal to the range beginning, no numbers outside the range 1-9, no commands other than `bet`, `retire`, `claim`, and correct number of arguments: `bet` taking 1 or 2 args, and the latter two commands taking no arguments. Floating point errors are acceptable.

This is code-golf with the shortest answerer in bytes winning. No standard loopholes, please.

# Answer
# JavaScript (ES6), 110 bytes

A function taking either `(command, value)` or `(command, min_value, max_value)`.

Returns `[chosen_number, profit]` for *bet*, `0` for *retire*, or the final balance for *claim*.

```
(c,x,y)=>c[3]?c[5]?b=0:t:[k=-~(Math.random(b=b*2||1)*9),-t+(t+=(k<x|k>(y||x)?-2:1)*(y?b+(~y+x)*b/10:b))]
b=t=0

```

Try it online!
> 3 votes

# Answer
# Python 3, 279 bytes

```
import random as o
d=m=0;t=1
s=eval(input())
for x in s:c,r=x[0],x[1:];exec({'bet':'if len(r)>1:r=range(r[0],r[1]+1);d=1\nh=o.randint(1,9);k=[t,t-t*(r[-1]-r[0]+1)/10][d];k=[-k,k][h in r]\nif not(d or(h in r)):k+=k\nprint(h,k);m+=k;t*=2','retire':'t=1','claim':'print(m);1/0'}[c])

```

Try it online!

Takes a 2D list as input, this is a full program which will prompt for input. Exits on zero division error on claim.
> 0 votes

---
Tags: code-golf, game, interactive
---