title: Numbers Manipulation challenge

text:
# Question
Title: Numbers Manipulation challenge
Use any programming language to generate two random digits between 1 and 9 (including both). Then your program should display:

* in the first line: the first random digit,
* in the second line: the second random digit,
* in the third line: a number whose tens and units digits are the first and second random digits respectively,
* in the fourth line: the number from the third line raised to the power of 2.

For example, if digits "9" and "2" were generated, your program should display exactly:

```
9
2
92
8464

```

# Answer
# 05AB1E, ~~14~~ 11 bytes

```
2F9LΩ=}J=n,

```

-3 bytes thanks to *@Emigna*.

Try it online.

**Explanation:**

```
2F    }        # Loop 2 times:
  9LΩ          #  Create a list in the range [1,9], and pick a random element from it
     =         #  Output it (without popping it from the stack)
       J       # Join them together
        =      # Output it (without popping it from the stack)
         n     # Take it to the power of 2
          ,    # And output it as well

```

---

**11 bytes alternative:**

```
9LãΩ©`®JDn»

```

Try it online.

**Explanation:**

```
9L             # List in the range [1,9]
  ã            # Cartesian product with itself: [[1,1],[1,2],[1,3],...,[9,7],[9,8],[9,9]]
   Ω           # Take a random element from it
    ©          # Store it in the register (without popping)
     `         # Pop and push both items as separated items onto the stack
      ®        # Retrieve the list of digits from the register again
       J       # Join them together to a single 2-digit number
        Dn     # Duplicate it, and take the power of 2 of the copy
          »    # Merge all values on the stack by newlines (and output implicitly)

```
> 2 votes

# Answer
# , ~~48~~ 47 bytes

```
cat(x<-sample(9,2,T),y<-x%*%c(10,1),y^2,fill=1)

```

Try it online!

Thanks to J.Doe for golfing down a byte.
> 6 votes

# Answer
# Japt, ~~14~~ 13 bytes

*-1 Byte from @Oliver*

```
2ÆÒ9ö
pU¬Uì ²

```

---

```
2ÆÒ9ö
pU¬Uì ²     Full program
-----------------------------------------
2Æ            Range [0,2) and map
   9ö         Random number in range [0, 9)
  Ò           increased by 1
              This result is assigned to U

p            Push into U
 U¬          Elements in U joined
   Uì ²      and elements joined squared
             Implicit output each element
             separated with new line -R

```

Try it online!
> 5 votes

# Answer
# Vim, 43 bytes

```
:%!$RANDOM

:s/0//g
2f:y2hVpo*<C-r>*=*<C-r>*0**<C-r>*0
*<Esc>*kYPa

```

Try it online!

Not the right tool for the job. This produces *most likely* the desired output

Step by step:

* `:%!$RANDOM` `Enter` `Enter`
Produces a string like `/bin/bash: 25266: command not found`
* `:s/0//g`
removes all zeroes
* `2f:y2hVp`
moves the cursor to the colon after the number, copy the last two digits and replace the entire string with those
* `o` `Ctrl`+`R` `=` `Ctrl`+`R` `0*` `Ctrl`+`R` `0` `Enter`
add a new line and evaluate an expression. In this case, I'll multiply the number in register 0 (the one that was just copied) with itself.
* `Esc` `kYPa` `Enter`
Copy the upper line and paste it above. The cursor ends up in the first line, on the first character. Now we just have to append a line break to it

Limitations: If the result of `$RANDOM` is a number with less than two non-zero digits, this will not produce the desired output
> 5 votes

# Answer
# C (gcc), ~~68~~ 67 bytes

*-1 byte thanks to cleblanc*

```
f(r){r=rand()%81*10/9+11;printf("%d\n%d\n%d\n%d",r/10,r%10,r,r*r);}

```

Try it online!
> 4 votes

# Answer
# K (oK), 28 bytes

```
t:2?10;t,:10/t;$t,:t[2]*t[2]

```

**Explanation**

```
t:2?10                       //define t as two random numbers from 1-10
       t,:10/t               //join the base 10 joining of the elements of t to t
                 t,:t[2]*t[2]//join the square of the index 2 element to t
               $            //String each element of the result (to output on newlines)

```

Try it online!

**Cleaner Output, 32 bytes**

```
t:2?10;t,:10/t;`0:$t,:t[2]*t[2];

               `0:               //Cleanly prints the strings

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~83~~ 76 bytes

-5 bytes thanks to nwellnhof.

```
from random import*
k=randint(9,89)*10//9+1
[*map(print,[k//10,k%10,k,k*k])]

```

Try it online!
> 3 votes

# Answer
# Perl 6, 39 bytes

```
{.comb,$_,$_²}([~] roll 1..9: 2)>>.put

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 67 bytes

```
f=_=>(n=Math.random()*90+10|0)%10?(n/10|0)+`
${n%10}
${n}
`+n*n:f()

```

Try it online!
> 3 votes

# Answer
# PowerShell, ~~48~~ 45 bytes

```
($a,$b=1..9*2|Random -c 2)
($x="$a$b")
+$x*$x

```

Try it online!

Concatenates two ranges `1..9` together, pipes that to `Get-Random` with a `-c`ount of `2` to pull out two elements, stores them into `$a` and `$b`, and encapsulates that in parens to place a copy of them on the pipeline.

Next we string concatenate `$a$b` and store it into `$x`, again placing in parens to put a copy on the pipeline. Finally we take `$x` squared and leave it on the pipeline.

All the results are gathered from the pipeline and an implicit `Write-Output` gives us newlines between elements for free.

*Saved 3 bytes thanks to mazzy.*
> 3 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
9ṗ2XṄ€ḌṄ²

```

Try it online!

### How it works

```
9ṗ2XṄ€ḌṄ²  Main link. No arguments.

9          Set the return value to 9.
 ṗ2        Promote 9 to [1, ..., 9] and take the second Cartesian power, yielding
           [[1, 1], [1, 2], ..., [9, 8], [9, 9]].
   X       Pseudo-randomly select one of the pairs.
    Ṅ€     Print each integer in the pair, followed by a newline.
      Ḍ    Undecimal; convert the integer pair from base 10 to an integer.
       Ṅ   Print the integer, followed by a newline.
        ²  Take the square.
           (implicit) Print the last return value.

```
> 3 votes

# Answer
# Pyth, 14 bytes

```
^
i,
hO9
hO9T2

```

Note that the newlines are significant. Try it online here.

Explanation, with newlines replaced with ¶ character:

```
^¶i,¶hO9¶hO9T2   Implicit: T=10

      O9         Choose a random number in [0-9)
     h           Increment
    ¶            Output with newline - value printed is yielded as expression result
        ¶hO9     Do the above again
   ,             Wrap the two previous results in a two-element array
  i         T    Convert to decimal from base 10
 ¶               Output with newline
^            2   Square the previous result, implicit print

```
> 3 votes

# Answer
# Ruby, 41 bytes

```
puts [(a=11+10*rand(81)/9)/10,a%10,a,a*a]

```

Try it online!
> 3 votes

# Answer
# T-SQL, 142 105 115 114 96 78 bytes

```
DECLARE @ int=RAND()*9+1,@a int=RAND()*9+1SELECT @,@a,10*@+@a,POWER(10*@+@a,2)

```

*-37 bytes: Realized I could just use two different random numbers and use the first digits from each!*
*+10 bytes: Edited to meet requirements of range from 1-9, instead of 0-9*
*-1 byte: Changed RIGHT() to LEFT() in @b*
*-18 bytes: Various changes suggested by BradC*
*-18 bytes: More changes suggested by BradC*

Ungolfed:

```
-- Setting RAND() separately in these produces different numbers.
-- [RAND() * b + a] sets the range for a random number, from a to b inclusive.
-- Declaring as an int removes the numbers after the decimal.
DECLARE @ int = RAND() * 9 + 1,
        @a int = RAND() * 9 + 1

SELECT @,                       -- first random digit
       @a,                      -- second random digit
       10 * @ + @a,             -- multiply first digit by ten, and add second
       POWER(10 * @ + @a, 2)    -- third digit squared

```
> 3 votes

# Answer
# Python 2, ~~84~~ 75 bytes

```
from random import*
k=randint(9,89)*10/9+1
for x in k/10,k%10,k,k*k:print x

```

Try it online!

---

Saved

* -1 bytes, thanks to Erik the Outgolfer
* -8 bytes, thanks to nwellnhof
> 2 votes

# Answer
# Java 8, ~~99~~ ~~98~~ ~~90~~ ~~81~~ 80 bytes

```
v->{int i=81;i*=Math.random();return(i=i*10/9+11)/10+"\n"+i%10+"\n"+i+"\n"+i*i;}

```

-8 bytes after being inspired by *@Arnauld*'s JavaScript answer.
-9 bytes thanks to *@nwellnhof*.

Try it online.

**Explanation:**

```
v->{                        // Method with empty unused parameter and no return-type
  int i=81;i*=Math.random();//  Create a random integer `i` in the range [0,81)
  return(i=i*10/9+11)       //  Set `i` to 10 times `i`, integer-divided by 9, and 11 added
        /10+"\n"            //  Return the first digit of `i`, a newline,
        +i%10+"\n"          //         the last digit of `i`, a newline,
        +i+"\n"             //         `i` itself, a newline,
        +i*i;}              //         and `i` multiplied by itself
                            //         All concatted to each other

```
> 2 votes

# Answer
# Charcoal, 16 bytes

```
≔⭆²⊕‽⁹θ↓θθ⸿ＩＸＩθ²

```

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

```
≔⭆²⊕‽⁹θ

```

Generate two random characters in the range `1` to `9`.

```
↓θ

```

Output them downwards i.e. on separate lines.

```
θ⸿

```

Output them horizontally on their own line.

```
ＩＸＩθ²

```

Cast to integer, square, cast back to string for implicit print.
> 2 votes

# Answer
# C# (.NET Core), 130 129 109 98 bytes

```
var r=new Random();int a=r.Next(1,10),b=r.Next(1,10),c=a*10+b;Console.Write($"{a} {b} {c} {c*c}");

```

Try it online!

*-1 byte: edited console output to use wildcards (thanks to Logern)*
*-20 bytes: changed* `r` *to* `var` *from* `Random`*, changed format of* `c`*; fixed* `r.Next()` *operators (thanks to LiefdeWen)*
*-11 bytes: changed format of* `c` *(thanks to user51497)*

Ungolfed:

```
var r = new Random();                   // initializes random number generator
int a = r.Next(1, 10),                  // gets random number between 1 and 9 inclusive
    b = r.Next(1, 10),                  // gets random number between 1 and 9 inclusive
    c = a * 10 + b;                     // concatenates a and b into one two-digit number
Console.Write($"{a} {b} {c} {c*c}");    // writes a, b, c, and c^2 to the console

```
> 2 votes

# Answer
# TI-BASIC, 27 bytes

```
11+int(89rand
Disp iPart(.1Ans),10fPart(.1Ans),Ans,Ans²

```

(can generate a 0 in the 2nd random number)

Uses kamoroso94's Disp layout, but makes use of TI-BASIC integer compression. Generating the 2 random integers as a single compressed integer and extracting them via iPart and fPart allows for shaving several bytes. It's possible to generate the random integers seperately in the same number of bytes by creating them simultaneously in a list:

```
1+int(9rand(2

```

But the repeated calls to the list via Ans(1) and Ans(2) end up taking many more bytes than the integer compression technique. It's also important to note that rand is generally advisable over randInt( for random integer generation as they either use equivalent bytes, or rand will be shorter when the lower bound is 0, and rand has the added flexibility of list generation.
> 1 votes

# Answer
# PHP, 64 bytes

```
<?$d=($c=(10*($a=rand(1,9))+$b=rand(1,9)))*$c;echo"$a
$b
$c
$d";

```

Try it online!
> 0 votes

# Answer
# Retina, 43 bytes

```

100*
L$`
$.`
A`0
G?`..
\*\L`.
..
$.($&*$&*

```

Try it online! Explanation:

```

100*
L$`
$.`

```

Count from 0 to 99.

```
A`0

```

Delete multiples of 10.

```
G?`..

```

Pick a random 2-digit number.

```
*\L`.

```

Output the digits separately.

```
\

```

Output the number.

```
..
$.($&*$&*

```

Square and implicitly output the number.
> 0 votes

# Answer
## MBASIC, ~~100~~ 86 bytes

```
1 DEF FNR(X)=INT(RND*X)+1:A=FNR(9):B=FNR(9):PRINT A:PRINT B:C=A*10+B:PRINT C:PRINT C^2

```

**Output**

```
5
8
58
3364

```
> 0 votes

# Answer
# TI-BASIC, 31 bytes

```
randInt(1,9→A
randInt(1,9→B
10A+B
Disp A,B,Ans,Ans²

```
> 0 votes

# Answer
# sfk, 99 bytes

```
rand 1 9 +setvar a +rand 1 9 +setvar b +tell -var "#(a)
#(b)
#(a)#(b)" +calc -var #(a)#(b)*#(a)#(b)

```

Try it online!
> 0 votes

# Answer
# perl -E, 45 bytes

```
$_=10+int rand 90;y/0/1/;say for/./g,$_,$_**2

```

This exploits the lack of a requirement that all random numbers should be picked with equal probability (it will pick numbers ending in 1 twice as often as ending in any other digit).
> 0 votes

# Answer
## Visual C#, ~~102 Bytes~~; 101 bytes

+2 Upper bound of Random.Next() exclusive, 10 instead of 9
-3 Thanks to LiefdeWen (var instead of Random)

```
var r=new Random();int x=r.Next(1,10),y=r.Next(1,10),z=x*10+y;Console.Write($"{x}\n{y}\n{z}\n{z*z}");

```

normal form:

```
var r = new Random();
int x = r.Next(1, 10),
    y = r.Next(1, 10),
    z = x * 10 + y;
Console.Write($"{x}\n{y}\n{z}\n{z * z}");

```

Try it online!

## Visual C#, ~~85 bytes 89 bytes~~ 91 Bytes

+4 bytes: fixed problem with 0 as second digits, borrowing the `*10/9+1` from other answers

+2 bytes: preventing numbers \<11

Even shorter solution

```
var r=new Random();int x=r.Next(9,89)*10/9+1;Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}");

```

normal form:

```
var r = new Random();
int x = r.Next(9, 89)*10/9+1;
Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}");

```

Try it online!
> 0 votes

# Answer
# Red, 69 bytes

```
prin reduce[x: random 9 n:"^/"y: random 9 n z: do rejoin[x y]n z * z]

```

Try it online!
> 0 votes

# Answer
# MathGolf, 9 bytes

```
2æ8w)o§o²

```

Try it online!

## Explanation

For the example, the first random integer is 4, the second is 7.

```
2æ         Start for-loop of length two, with the next 3 chars as the body
  8w       Random non-negative integer less than or equal to 8
    )      Increment by 1
     o     Output without popping (stack is unchanged)
           For loop ends, stack is now [4, 7], the first two lines have been printed
     §     Concatenate the two numbers on the stack (stack is [47])
      o    Output without popping (stack is unchanged)
       ²   Square number and output implicitly

```
> 0 votes

# Answer
## Batch, 95 bytes

```
@set/at=%random%%%9+1,u=%random%%%9+1,n=t*10+u,p=n*n
@for %%a in (%t% %u% %n% %p%)do @echo %%a

```

`%random%` isn't a real variable, it's interpolated at parse time, so you need the `%`s even inside `set/a`. (Also don't try using it in a loop!)
> 0 votes

---
Tags: code-golf, random
---


# Question
Title: Count the corners, edges and faces of a cut cube
Coming from this sandbox post

This is inspired from an 8th graders math test

# Intro

We have a cube with following corners

```
A(0, 0, 0)
B(1, 0, 0)
C(1, 1, 0)
D(0, 1, 0)
E(0, 0, 1)
F(1, 0, 1)
G(1, 1, 1)
H(0, 1, 1)

```

This cube clearly has 8 corners, 12 edges and 6 faces. If we now cut off corner G, such that our cut plane goes exactly through the middle of each adjacent original edge, we add 2 new corners, 3 new edges and one new face. Please enjoy this hand drawn piece of art, for better clarification

# Input

Given a list of corners (in this example identified by A-H), that will be cut off, compute the new number of corners, edges and faces.

You make take the input in any form you like, as long as it responds to the same corners (e.g. instead of A-H you can use 1-8 or 0-7, you can assume it to be a list, csv, whatever)

You can assume the list to be distinct (every corner will appear once at most), but it may be empty. The list will never contain non existing corners.

# Output

Output three numbers corresponding to the number of corners, edges and faces. Output as a list is explicitly allowed. Trailing whitespaces are allowed

Examples

```
{}        ->  8, 12,  6 (empty list)
{A}       -> 10, 15,  7
{A,C}     -> 12, 18,  8
{A,C,F}   -> 14, 21,  9
{A,B,C}   -> 12, 19,  9
{A,B,C,D} -> 12, 20, 10

```

Finally, this is codegolf, thus the shortest answer in bytes wins. Please refrain from standard loopholes.

# Answer
# Jelly, 23 bytes

```
3R×L+“©®€‘ɓŒcn/€§ċ1;`Żạ

```

A monadic Link. Input is a list of corners of the cube as Cartesian co-ordinates (cube aligned with the co-ordinate system). Output is a list of integers, `[faces, corners, edges]`.

**Try it online!**

### How?

```
3R×L+“©®€‘ɓŒcn/€§ċ1;`Żạ - Link: list of lists, C          e.g. [[0,1,1],[1,1,0],[1,1,1],[0,0,0]] -- this could represent "FHGA"
3R                      - range of 3                           [1,2,3]
   L                    - length of C                          4
  ×                     - multiply                             [4,8,12]
     “©®€‘              - list of code-page indices            [6,8,12]
    +                   - add                                  [10,16,24]
          ɓ             - start a new dyadic chain, f(C,X) where X is the above result
           Œc           - pairs of C                           [[[0,1,1],[1,1,0]],[[0,1,1],[1,1,1]],[[0,1,1],[0,0,0]],[[1,1,0],[1,1,1]],[[1,1,0],[0,0,0]],[[1,1,1],[0,0,0]]]
              /€        - reduce €ach with:
             n          -   (vectorising) not equal?           [[1,0,1],[1,0,0],[0,1,1],[0,0,1],[1,1,0],[1,1,1]]
                §       - sum each                             [2,1,2,1,2,3]
                 ċ1     - count ones                           2
                   ;`   - concatenate with itself              [2,2]
                     Ż  - prepend a zero                       [0,2,2]
                      ạ - absolute difference with X           [10,14,22]

```

---

If the corners must be "ordered" as they are in the question then this works with integers 0-7 as A-H for 25 bytes: `3R×L+“©®€‘ɓŒc^/€ḟ2<5S;`Żạ` (reduces using XOR, filters out twos, then counts those less than five).
> 2 votes

# Answer
# Perl 6, ~~59~~ 58 bytes

```
{6+@_,|((2,3 X*4+@_)X-(@_ X~@_)∩~<<ords "% 286
>C/")}

```

Try it online!

Uses the numbers `0` to `7` to represent the corners. I probably should have matched them up to the same order as in the question... oops? Outputs a list in the order `faces, corners, edges`.
> 2 votes

# Answer
# Charcoal, ~~48~~ 45 bytes

```
≔Ｅθ↨℅ι²η≔⊘№⭆η⭆ηΣＥι↔⁻§λξν1ηＩＥ⟦⁶⁻⁸η⁻¹²η⟧⁺ι×⊕κＬθ

```

Try it online! Link is to verbose version of code. Uses digits `0-7` to represent the letters `ABDCEFHG` in the diagram. Outputs in the order faces, corners, edges. Explanation:

```
≔Ｅθ↨℅ι²η

```

Take the ASCII code of each character and convert it to base 2.

```
≔⊘№⭆η⭆η

```

Take the cartesian product of the list of base 2 numbers with itself.

```
ΣＥι↔⁻§λξν1η

```

XOR the pairs of base 2 numbers together and sum the number of 1 bits. Count how many pairs have a sum of 1 and divide that by 2. This gives the number of coincident corners.

```
ＩＥ⟦⁶⁻⁸η⁻¹²η⟧⁺ι×⊕κＬθ

```

Calculate and print the number of faces, corners and edges.
> 2 votes

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

```
a=>[a.map(u=>a.map(v=>j-=!!'ABCDAEFGHEFBCGHD'.match(u+v),n++,j+=2),n=j=6)|2+j,n+j,n]

```

Try it online!
> 2 votes

---
Tags: code-golf
---


title: Hotel room numbering

text:
# Question
Title: Hotel room numbering
Given an input of a "hotel" in ASCII art with a single room marked, output the room number according to certain rules.

Here's an example of an ASCII hotel:

```
               ##
               ##
#####          ##
#####  ######  ##
#####  ######  ##
#####  ######  ##

```

Here are a few more things about the ASCII hotels:

* Each "building" is represented by a rectangle of `#` characters, where each `#` represents a "room".
* The above hotel consists of three buildings. Each building is separated by two columns of spaces, and the lowest "floor" will always be on the last line.
* Each building will always have anywhere from 1-9 "floors" (rows) and 1-9 "rooms" on each floor. There will also always be 1-9 buildings.
* Rooms are numbered as follows: `[building #][floor #][room on floor #]`. For example, let's mark a few rooms in the above drawing:

```
               ##
               ##
#####          ##
#####  ####$#  ##
##%##  ######  ##
#####  ######  #@

```

The room marked with the `%` is room 123 (building 1, floor 2, 3rd room on floor). Similarly, the room marked with the `$` is room 235, and the `@` is room 312.
* Buildings, floors, and "nth room on floor"s are always 1-indexed.

The input will consist of an ASCII hotel with a single room replaced with an asterisk (`*`). This is the room for which you must output the room number. The input must be taken as a single string, but you may use commas as line separators instead of newlines (in case your language of choice cannot take multiline input or if it's shorter to take single-line input). You may optionally require a trailing comma/newline. You may also pad lines with trailing spaces to make the input a complete rectangle.

Since this is , the shortest code in bytes wins.

Test cases (contained within a single code block to conserve vertical space):

```
Input:
*

Output: 111

Input:
#  #  *  #  #

Output: 311

Input:
#####
#####
####*
#####
#####

Output: 135

Input:
         #####
         #####           ######
         #####           ######
#  #  #  #####  #  #  #  ######  *

Output: 911

Input:
#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########

Output: 523

Input:
           #
           *
           #
           #
           #
           #
           #
           #
#########  #  #

Output: 281

Input:
                        ########*
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
#  #  #  #  #  #  #  #  #########

Output: 999

```

# Answer
## CJam, ~~34~~ 31 bytes

```
qN/W%zSf-La%{_{s'*&}#_)@@=}3*;\

```

This requires the input to be padded to a rectangle with spaces.

Try it online! Alternatively, run all test cases.

### Explanation

```
qN/      e# Read input and split into lines.
W%z      e# Rotate 90° counter-clockwise.
Sf-      e# Remove all spaces from the rows.
La%      e# Split into buildings. We've now got a 3D array of rooms, where the first
         e# dimension is the building, the second the room number and the third is the
         e# the floor number.
{        e# Run this block three times. At each stage it will find the index of the "*"
         e# along the current dimension and leave the element at that index on the stack
         e# for the next round...
  _      e#   Duplicate the current array.
  {      e#   Find the index of the first element where this block yields something
         e#   truthy...
    s    e#     Flatten into a single string.
    '*&  e#     Set intersection with "*".
  }#
  _)     e#   Duplicate the index and increment it, because the results should be 1-based.
  @@=    e#   Pull up the array and the other copy of the index and select the
         e#   corresponding element.
}3*
;\       e# We've now got the building, room and floor index on the stack, as well as the
         e# "*" character itself. We discard the character and swap the room and the floor
         e# floor number. When the three indices are printed back-to-back at the end of
         e# the program, that will yield the desired result.

```
> 11 votes

# Answer
# Pyth, 34 bytes

```
LxKh/#\*b\*jkhM[//<hJ_.zyJd2xJKycK

```

Demonstration

This uses a golfing trick I've never used before: Assigning to a variable (`K`) inside a function (`y`) to save a partial result from that function.

### Explanation:

```
LxKh/#\*b\*jkhM[//<hJ_.zyJd2xJKycK
L                                     Define y(b):      (b is a list of strigs)
    /#\*b                             Filter b for strings containing '*'
   h                                  Take the first such string
  K                                   Store it in K
 x       \*                           And return the index of '*' in that string.
                      .z              Take the input as a list of strings
                     _                Reverse it (bottom to top)
                    J                 Store in J
                   h                  Take the bottommost row
                        yJ            Find y(J). This is the index in whichever
                                      row of J has the * of the *. Also store
                                      that row in K.
                  <                   Slice J up to that index.
                 /        d           Count the number of spaces
                /          2          Divide by 2. This is the building number.
                            xJK       Take the index in J of K. This is the floor.
                                cK    Chop K on whitespace.
                               y      Find the index in whatever element of K has
                                      the * of the *. This is the room number.
                                      This also overwrites K, but we don't care.
               [                      Gather the above into a list.
             hM                       Convert 0-indexing to 1-indexing.
           jk                         Concatenate. Print implicitly.

```
> 9 votes

# Answer
# JavaScript (ES6), ~~142~~ 136 bytes

```
h=>h.split`
`.reverse(r=0).map((t,i,l)=>r?0:(f=i+1,b=1,l[o=0].slice(0,r=t.indexOf`*`+1).replace(/  /g,(_,s)=>o=++b&&s+2),r-=o))&&[b]+f+r

```

*6 bytes saved thanks to @nderscore!*

## Explanation

```
h=>
  h.split`
`                            // get each line of the input string
  .reverse(                  // reverse the lines to make getting the ground floor easy
    r=0)                     // initialise r to 0
  .map((t,i,l)=>             // for each line of the reversed input string
    r?0:(                    // if the marked room has not been found yet:
      f=i+1,                 // f = floor number
      b=1,                   // b = building number, default to 1
      l[o=0].slice(0,        // get the substring of 0 to the marked room, default o to 0
        r=t.indexOf`*`+1)    // r = absolute index of room + 1 (or 0 if not found)
      .replace(/  /g,(_,s)=> // count the spaces between buildings
        o=++b&&s+2),         // increment b, o = index of marked room's building
      r-=o                   // make r relative to the room's building
    )
  )
  &&[b]+f+r                  // output the result ([b] casts b to a string)

```

## Test

```
var solution = h=>h.split`
`.reverse(r=0).map((t,i,l)=>r?0:(f=i+1,b=1,l[o=0].slice(0,r=t.indexOf`*`+1).replace(/  /g,(_,s)=>o=++b&&s+2),r-=o))&&[b]+f+r
```

```
<textarea id="input" rows="8" cols="60">#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 8 votes

# Answer
# awk, 70

```
!i{i=index($0,"*")}i{$0=substr($0,0,i);f++}END{print NF f length($NF)}

```

Example:

```
Input:
#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########

While no * was found, do nothing.
#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
A * is found in column 14. From now on, truncate and increment the floor counter.
#  #  ##  ###  ##*    f=1
#  #  ##  ###  ###    f=2
Awk automatically splits $0 into space separated fields, counted by builtin NR.
In the end, NR and f hold hotel and floor number.
The room number is the length of the last hotel.

```
> 7 votes

# Answer
# C, 131 130 119 113 bytes

```
b,f,i,j=111;main(c){for(;c=~getchar();)c&32?f+=10,b=i=0:++i<j?c%3?f=j,j=i:c&2?b+=50-b%50:++b:0;printf("%d",b+f);}

```

Takes input on stdin; input must *not* have a terminating newline. Assumes 2's complement.

Ungolfed:

```
// Declare variables (default type is int) and initialize, by default to 0:
b,    // Building number (multiplied by 100, 0-based) + room number (0-based)
f,    // Floor (111-based, multiplied by 10)
i,    // Current column of input character within line (1-based)
j = 111; // Column of asterisk character once found (1-based), 111 before then
main (c)    // Declare main function and variable c to hold input character
{
  for (;    // Loop on input
    c = ~getchar();  // Read a character into c, bitwise inverted to break
                     // EOF (numeric value -1). This means that following
                     // operations (on the ASCII value of the input) are
                     // also inverted.
    )
    c & 32 ?              // Newline?
      f += 10, b = i = 0 :  // Increment floor; reset building, room, column
      ++i < j ?             // Increment column; before asterisk, or asterisk not yet found?
        c % 3 ?               // Asterisk character?
          f = j, j = i :        // Reset floor and record column
          c & 2 ?               // Space character?
            b += 50 - b % 50 :    // Increment building and reset room
            ++b :                 // Otherwise, # character; increment room
        0;                    // After asterisk; do nothing
  printf("%d", b + f);  // Write out results
}

```
> 6 votes

# Answer
# Stackgoat, 73 bytes \[non-competing\]

Stackgoat is a stack-based language that has nothing to do with goats.

```
y'#ZGDYZG'*iVXsV@"\\*"ZGN2/1+y'#ZG' ZG'q:Nq'*i-yXsq'*i@"[#*]+"M0M1-@'*i1+

```

It's a fairly new language so let me know if they're any problems with it. I gave myself quite a headache figuring this out so this is about as much as I'm golfing this.

### Explanation

This program has 3 parts for each 3 digits of the room number

```
y'#ZG    // Remove all # from input
D        // Duplicate
YZG      // Remove all spaces
'*i      // Index of *
V        // Reverse stack
Xs       // Split on spaces
V@       // Unreverse, item at *'s index
"\\*"ZG  // Remove all *s
N        // Get length
2/1+     // Divide by 2, add 1

y'#ZG    // Remove all #
' ZG     // Remove all spaces
'q:      // Store in q
N        // Get length
q'*i     // *'s index in q
-        // Subtracted from length

yXs      // Split on newlines
q'*i     // Get index of * in q
@        // Get indexed-th line
"[#*]+"M // Match all buildings
0M       // Get *'s building no.
1-       // Subtract one
@        // nth building at right line
'*i      // *'s index
1+       // Added to one

```
> 4 votes

# Answer
# Ruby, 103

```
->n{r=x=b=0
n.lines{|s|(t=s=~/\*/)&&(x=t;r=($`.reverse+' ')=~/ /)
r+=10;b=s[0..x].count" "}
b*50+r+101}

```

Ungolfed in test program

```
g=->n{
  r=x=b=0
  n.lines{|s|                  #for each line in n
    (t=s=~/\*/)&&              #if the line contains an asterisk
      (x=t                     #record its position in x. $` is a special variable containing the part of the string to the left of the last match made.
      r=($`.reverse+' ')=~/ /) #reverse $` and search for the index of the first space to find room number (before the search a space is appended in case it is 1st building.)
    r+=10                      #increment r by 10 for the floor number (obviously this will have been reset to the row ith the asterisk by the previous line)
    b=s[0..x].count" "}        #count the number of spaces left of x in the current row to find building number (loop will exit with calc from bottom row, which is the correct one.)
b*50+r+101}                    #multiply number of spaces by 50 to get 1st digit, add r for 2nd and 3rd digit. Then add 101 to correct 1st and 3rd digits from 0-indexed to 1-indexed.

puts g["
*"]

puts g["
#  #  *  #  #"]

puts g["
#####
#####
####*
#####
#####"]

puts g["
         #####
         #####           ######
         #####           ######
#  #  #  #####  #  #  #  ######  *"]

puts g["
#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########"]

puts g["
           #
           *
           #
           #
           #
           #
           #
           #
#########  #  #"]

puts g["
                        ########*
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
#  #  #  #  #  #  #  #  #########"]

```
> 4 votes

# Answer
# JavaScript (ES6), 121

```
x=>x.split`
`.reverse().map((r,f,h,a=r.indexOf`*`)=>x=~a?(h=h[0].slice(0,a).split`  `).length+[f+1]+-~h.pop().length:x)|x

```

**Less golfed and explained**

```
H=x=>x.split`\n` // split in lines
  .reverse() // reverse, so we can scan bottom up
  .map( (r,f,h) => // exectute for each line
         // r is the current row
         // f in the row index, so that f+1 is the floor number
         // h is the reversed array, h[0] is the bottom floor
       ~(a=r.indexOf`*`) // a is the position of '*' in the line, if found - else 0
       && ( // if a >= 0
         h = h[0]        // bottom floor line
             .slice(0,a) // ... truncated at position of '*'
             .split`  `, // ... and splitted at '  ', as an array
         x = h.length  // the array len is the building number
             + [f+1]   // floor number, using [] to force string concatenation
             + -~ h.pop().length // the length of the last array element is the number
                                 // of chars in the block before '*'
                                 // increment by 1 to get the room number
      )
  )
  && x // return the found value

```

**TEST**

```
H=x=>x.split`
`.reverse().map((r,f,h,a=r.indexOf`*`)=>x=~a?(h=h[0].slice(0,a).split`  `).length+[f+1]+-~h.pop().length:x)|x

// test
console.log=x=>O.textContent+=x+'\n';

;[['*',111],['#  #  *  #  #',311],
[`#####
#####
####*
#####
#####`,135],
[`         #####
         #####           ######
         #####           ######
#  #  #  #####  #  #  #  ######  *`,911],
[`#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########`,523],
[`           #
           *
           #
           #
           #
           #
           #
           #
#########  #  #`,281],
[`                        ########*
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
#  #  #  #  #  #  #  #  #########`,999]]
.forEach(t=>{
  var i=t[0],k=t[1],r=H(i)
  console.log(i+'\n' + (k!=r?'Error '+r+' expected '+k:'Ok '+r)+'\n')
})
```

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

# Answer
## Python 2.7, ~~153~~ 168 characters

I liked this challenge! If a Python list is ok as input (see testsuite for examples), this solution works.

*Edit 2016-01-05:* added one line (10 characters) to split the string in multiline.

Short explanation:

* `t` is the row in which the room is located (counted from the top-row as array index = 0);
* `i` is the index of the room in its row;
* the building is calculated as the number of double white spaces in the bottom row until `i`;
* floor is the number of row minus `t`;
* room is the index of the first double whitespace in the reversed string from `i` until the beginning of the floor with the room, appended by a whitespace to cover for the case that the room is in the first building.

Code:

```
def r(l):
 l=h.split(",")
 a,w,s="*","  ",str
 t=l.index(filter(lambda c:a in c,l)[0])
 i=l[t].find(a)
 return s(l[-1][:i].count(w)+1)+s(len(l)-t)+s((l[t][i::-1]+w).find(w))

```

Testsuite:

```
cases = [
         (["*"], 111),
         (["#  #  *  #  #"], 311),
         (["#####","#####","####*","#####","#####"], 135),
         (["         #####","         #####           ######","         #####           ######","#  #  #  #####  #  #  #  ######  *"], 911),
         (["#","#  #","#  #  ##","#  #  ##  ###","#  #  ##  ###  #####","#  #  ##  ###  ##*##  ########","#  #  ##  ###  #####  ########"], 523),
         (["           #","           *","           #","           #","           #","           #","           #","           #","#########  #  #"], 281),
         (["                        ########*","                        #########","                        #########","                        #########","                        #########","                        #########","                        #########","                        #########","#  #  #  #  #  #  #  #  #########"], 999)
        ]

for idx,(hotel,roomnr) in enumerate(cases):
    output=r(hotel)
    if str(output)==str(roomnr):
        result="SUCCESS"
    else:
        result="FAILURE!!!"
    print "Case {} gives output: {}. Correct output is: {}. Result: {}".format(idx,output,roomnr,result)

```
> 3 votes

# Answer
# Snails, 32 bytes

```
A
\*{l\#,|r,9d.,{|=~r,9{|l.,\ \#

```
> 3 votes

# Answer
# C, ~~142~~ ~~138~~ 137 bytes

```
#include <stdio.h>
f,b,x,p=110;main(c){while(~(c=getchar()))c<11?f+=c,b=x=0:x++<p?++b,c&2?c&8?f=p,p=x:0:(b+=50-b%50):0;printf("%d",b+f);}

```

(~~123~~ ~~119~~ 118 bytes + 19 for `#include` line)

I stole the value merging idea from ecatmur, but I've merged them in quite a different way (~~saves 8 bytes in the end~~). This also makes the same assumption that `EOF == -1`.

The input is taken from stdin, and must not have whitespace or newlines after the last building on the last line, so an example input would be:

```
printf "##\n##       #\n##  ##*  #\n##  ###  #" | ./hotel
# or for better visualisation:
printf "##\n##       #\n##  ##*  #\n##  ###  #" | tee /dev/fd/2 | ./hotel;echo ""

```

Breakdown:

```
// Globals initialise to 0
f,     // floor number * 10 + shift
b,     // building number * 100 + room number
x,     // current column
p=110; // will store column of * (must start >= 11*9-2, and 110 will be used later)
main(c){
    while(~(c=getchar()))              // For each character until EOF
        c<11                           //  Is \n? (10)
            ?f+=c,                     //   Add 10 to floor number
             b=x=0                     //   Reset building, room, column
            :x++<p                     //  Else, is column <= *?
                  ?++b,                //   Add to room number
                   c&2                 //   Is # or *?
                      ?c&8             //   If *:
                          ?f=p,p=x:0   //    Set floor to 110, set p to column
                      :(b+=50-b%50)    //   If ' ': go to next building
                  :0;
    printf("%d",b+f);                  // Result is building+room+floor+shift
}

```
> 2 votes

# Answer
## Haskell, ~~128~~ 125 bytes

```
l=length
f h|b<-snd$break(elem '*')$lines h,q<-fst(span(<'*')$b!!0)++"*"=l(last$words$q)+10*l b+l(words$take(l q)$last b)*100

```

Usage example: `f "# # * # #"` -\> `311`.

How it works:

```
b<-snd$break(elem '*')$lines h      -- split the input into a list of lines
                                    -- and assign b to the lines starting with
                                    -- the one that includes * up to the end,
                                    -- i.e. drop leading lines without the *
q<-fst(span(<'*')$b!!0)++"*"        -- assign q to the line with the *, but strip
                                    -- off all chars after the *

l(last$words$q)                     -- the room on floor number is the length of
                                    -- the last word of q
10*l b                              -- the floor number is 10 times the length of b
l(words$take(l q)$last b)*100       -- the hotel number is 100 times the number of
                                    -- words in the last line cut down to the
                                    -- length of q

                                    -- add for final room number

```
> 1 votes

# Answer
## Lua, 165 Bytes

```
l={}i=1while(l[i-1]~="")do l[i]=io.read()o=l[i]:find"%*"x=o or x y=o and i or y i=i+1 end print(#l[i-2]:sub(1,x):gsub("%S+%s*","#")*100+(i-y-1)*10+#l[y]:match"#-%*")

```

**Ungolfed**

```
l={}
i=1
while(l[i-1]~="")do
    l[i]=io.read()
    o=l[i]:find"%*" --find "*", and record:
    x=o or x        --position and
    y=o and i or y  --current floor
    i=i+1
end
print(#l[i-2]:sub(1,x):gsub("%S+%s*","#")*100 --[[Take last string of list, and then
                                                  take the substring up until the
                                                  asterisk. Substitute any substrings
                                                  that include nonspace characters
                                                  (%S+) followed by a minimum of 0 space
                                                  characters (%s*) with one character
                                                  (in this code snippet I chose # for no
                                                  particular reason.) Then take the length
                                                  of this string, with the # operator.
                                                  The %S+%s* regex and gsub do the bulk
                                                  of the magic.
                                                ]]
      +(i-y-1)*10                             --[[Total number of lines minus '*' floor
                                                  minus one.
                                                ]]
      +#l[y]:match"#-%*")                     --[[Find the substring on the asterisk floor
                                                  with '#' symbols preceding an asterisk.
                                                ]]

```
> 1 votes

# Answer
## CoffeeScript, 110 bytes & JavaScript, 121 bytes

```
(s)->s.split('\n').reverse().map((f,g)->f.split('  ').map((h,i)->r=h.indexOf('*');s=''+i+g+r if r>-1));111+1*s

```

## Readable

```
(s)->
    s.split '\n'
        .reverse()
        .map (f,fi)->
            f.split('  ')
                .map (h,hi)->
                    ri = h.indexOf('*')
                    s = ''+hi+fi+ri if ri>-1
    111+1*s

```

Basically same thing in Javascript:

```
(s)=>{s.split('\n').reverse().map((f,g)=>f.split('  ').map((h,i)=>{r=h.indexOf('*');r>-1?s=''+i+g+r:''}));return 111+1*s}

```
> 0 votes

# Answer
## Java, 231 Bytes

```
String a(String a){String[]b=a.split("\n");int i=0,c=b.length,m;String x,k=" ";for(;i<c;i++){x=b[c-1].substring(0,b[i].indexOf("*")+1);m=x.length();a=m>0?""+(m-x.replace(k+k,k).length()+1)+(c-i)+(m-x.lastIndexOf(k)-1):a;}return a;}

```

De-Golfed

```
 String a(String a) {
     String[] b = a.split("\n");                                // Split the input into floor lines
     int i = 0, c = b.length, m;                                // i=floor line counter c= number of floor lines
     String x, k = " ";
     for (; i < c; i++) {                                       // Loop through floor lines
        x = b[c - 1].substring(0, b[i].indexOf("*") + 1);       // x = part of bottom floor line up to '*' position in current line (Empty string when no '*')
        m = x.length();                                         // m = length of floor line part
        a = m > 0 ? "" + (m - x.replace(k + k, k).length() + 1) // if m>0 ('*' is on this line) set a=building no+floor no+room no.   building no calculated by replacing double space in x with single space and compare length to x (+1)
              + (c - i)                                         // floor number is total floor lines (c) - floor line loop counter (i)
              + (m - x.lastIndexOf(k) - 1) : a;                 // room number is m ('*' position in x) - position of last space in x (-1)
     }
     return a;                                                  // return the result at the end.
  }

```
> 0 votes

# Answer
# Powershell, 154 bytes

```
param($s)filter s{$s|sls $_ -a|% M*|% Le*}(($s-split'
')[-1]|% s*g 0('(?m)^.*\*'|s)|sls '^|  '-a|% M*).Count,('(?ms)(?<=\*.*)$'|s).Count,('#*\*'|s)-join''

```

Less golfed test script:

```
$f = {

param($s)

filter s{
    $s|sls $_ -AllMatches|% Matches|% Length
}                                   # select an array of lengths of all matches of the string $s by pattern $_

$hpos='(?m)^.*\*'|s                 # horizontal position of the room in the source string
$basement=($s-split"`n")[-1]        # basement floor string

$building=($basement|% substring 0 $hpos|sls '^|  ' -AllMatches|% Matches).Count
                                    # truncate the basement to the position of the room
                                    # and count all double spaces or a 'start of string'
$floor=('(?ms)(?<=\*.*)$'|s).Count  # count all 'end of line' after the room
$room='#*\*'|s                      # count all #, preceding the room, and room itself

$building,$floor,$room-join''

}

@(

,(@"
*
"@, 111)

,(@"
#  #  *  #  #
"@,311)

,(@"
#####
#####
####*
#####
#####
"@, 135)

,(@"
        #####
        #####           ######
        #####           ######
#  #  #  #####  #  #  #  ######  *
"@, 911)

,(@"
#
#  #
#  #  ##
#  #  ##  ###
#  #  ##  ###  #####
#  #  ##  ###  ##*##  ########
#  #  ##  ###  #####  ########
"@, 523)

,(@"
        #
        *
        #
        #
        #
        #
        #
        #
#########  #  #
"@, 281)

,(@"
                        ########*
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
                        #########
#  #  #  #  #  #  #  #  #########
"@, 999)

) | % {
    $n,$expected = $_
    $result = &$f $n
    "$($result-eq$expected): $result"
}

```

Output:

```
True: 111
True: 311
True: 135
True: 911
True: 523
True: 281
True: 999

```
> 0 votes

# Answer
# 05AB1E, 34 bytes

```
|€SζJðмõ¡εεR'*k>]DOZ©k>;ò®«sĀ€ƶ˜à«

```

Zip with string-lists is currently bugged. `€SζJ` could have been just `ζ` in the old Python legacy version of 05AB1E, but for some reason doesn't work in the Elixir rewrite version anymore.

Try it online or verify all test cases.

**Explanation:**

```
|                    # Take the input split by newlines
                     #  i.e. "   ###\n#  ###\n#  ###  ##\n#  ##*  ##"
                     #   → ["   ###","#  ###","#  ###  ##","#  ##*  ##"]
 €S                  # Convert each to a list of characters
   ζ                 # Zip, swapping rows and column
    J                # Join them together to a string again
                     #  → [" ###","    ","    ","####","####","###*","    ","    ","  ##","  ##"]
     ðм              # Remove all spaces
                     #  → ["###","","","####","####","###*","","","##","##"]
       õ¡            # Split on empty strings
                     #  → [["###"],[],["####","####","###*"],[],["##","##"]]
ε                    # Map each building to:
 ε                   #  Map each column of the building to:
  R                  #   Reverse the column
   '*k              '#   Get the 0-indexed index of "*"
      >              #   Increase it by 1 to make it 1-indexed
]                    # Close both maps
                     #  → [[0],[],[0,0,1],[],[0,0]]
 D                   # Duplicate the resulting list
  O                  # Sum each building
                     #  → [0,0,1,0,0]
   Z                 # Get the max (without popping)
                     #  → 1
    ©                # Store this max in the register (without popping)
     k>              # Get the index (+ 1) of this max in the sum-list
                     #  → 3
       ;             # Halve it
                     #  → 1.5
        ò            # Round it up to the nearest integer (bankers rounding)
                     #  → 2
         ®           # Retrieve the value from the register again
          «          # Merge the two digits together
                     #  → 21
           s         # Swap so the duplicate list is at the top again
            Ā        # Trutify (0 remains 0, every other integer becomes 1)
                     #  → [[0],[],[0,0,1],[],[0,0]]
             €       # For each building:
              ƶ      #  Multiply the integer with the 1-indexed index
                     #  → [[0],[],[0,0,3],[],[0,0]]
               ˜     # Flatten the list
                     #  → [0,0,0,3,0,0]
                à    # Pop the list, and get the max
                     #  → 3
                 «   # Merge it with the other two digits (and output implicitly)
                     #  → 213

```
> 0 votes

# Answer
# Dart, 165 bytes

```
F(List s)=>s.indexWhere((a)=>a.contains('*'));f(String s){var b=s.split('\n'),v=F(b),c=b[v].split('  '),w=F(c),x=c[w].indexOf('*')+1;return '${w+1}${b.length-v}$x';}

```

Try it online!
> 0 votes

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


title: Rearrangeable Code Bowling

text:
# Question
Title: Rearrangeable Code Bowling
# Code-Bowling Challenge

Write a program or function that produces the same output, no matter how you re-arrange the source code. *(Output can't be an error)*

---

# Pangram Scoring

* Your score is the amount of unique characters in your source code.

> A program with source code `AJB` would have a score of `3`
> A program with source code `AAJ` would have a score of `2`
> A program with source code `111` would have a score of `1`
* This is a variant. The program with the highest score wins!

*(For your convenience an automated scoring tool has been created **here**)*

---

## Challenge Rules

1. **Input**
The program/function can take an input, that's entirely optional though.
2. **Output**
This output can be *anything* you want, but it should be non-nil, non-null, non-empty, and non-error. *(Therefor output must be at least 1 byte)*
3. **Rearrangement**
No matter how the source code is re-arranged, the output should be the same.
Example:
Program: `ABJ` outputs `hello world`, as does programs: \[`AJB`, `JAB`, `JBA`, etc.\]

---

This is a variant. The program with the highest number of characters wins!

# Answer
> 18 votes
# Lenguage, 1,112,064 points if UTF-8

My program consists of every possible UTF-8 character. It prints out "Hello world", and uses 1.75 * 1076 yottabytes of space.

(To generate the program, you simply need to make a file with 17498005810995570277424757300680353162371620393379153004301136096632219477184361459647073663110750484 characters, ensuring that each possible UTF-8 character is in the file)

# Answer
> 14 votes
## Many languages, 2 points

```
0.

```

Produces `0.0` as `0.` or `.0`. Requires liberal number parsing that's OK with a decimal point at the start or end, assuming 0 for the missing integral or decimal part. `0000000.` would give the same score.

This also works in the following languages (in some cases with a different output, as indicated):

* Python REPL
* Javascript REPL
* MATLAB (produces `ans = 0`)
* Octave (produces `ans = 0`)
* MATL (produces `0`)
* CJam
* Retina (produces `0`)
* Stacked (produces `0`)

---

For Python, I think this is the only way to get a score above 1, as the possibilities can be exhausted.

* Any binary or unary operator will fail as the last character
* Any of `[](){}` require a match and will fail if the closing one comes first
* A tabs or space can't start a line. Newlines can't be used in REPL.
* A `,` can't be the first character
* A `#` placed first would comment everything and produce not output
* A starting `\` is an invalid line continuation
* Backticks (Python 2) must be paired, and them surrounding nothing is an error
* `$`, `!`, `?`, and `@` can't be used without other unusable characters

This leaves letters, digits, `_`, `.`, and quotes.

* With quotes, any non-string outside them gives an error.
* Letters with possible digits and `_` makes variable names, of which some permutation always doesn't exists.

The leaves digits and `.`. Permuting different digits gives a different number unless all the digits are `0`. So, I think zeroes and `.` is the only way to get a score above `1`. But, I don't know the Python lexer well, so I could be missing something.

# Answer
> 11 votes
## CJam, score 15

```
T U
V	LMOQR[]0q

```

Try it online!

Always prints `0000`:

* `0` just pushes a zero.
* `T`, `U`, `V` are variables which are pre-initialised to zero.
* `L`, `M`, `O`, `Q`, `R` are variables which are pre-initialised to an empty list, so they don't show up in the output.
* `[` and `]` may or may not wrap things in a list, but they don't have to be matched correctly and the output is flattened for printing anyway.
* `q` reads the input which is empty and hence doesn't show up in the output either.
* linefeed, space and tab are ignored by the parser.

# Answer
> 9 votes
# MATL, ~~3~~ ~~5~~ 6 points

*The idea to add whitespace was taken from Bijan's answer*.

```
lv
 T1

```

The code, or any permutation thereof, outputs three ones separated by newlines.

**Try it online!**

### Explanation

* Function `l` by default pushes number one to the stack.
* Literal `1` does the same.
* Literal `T` pushes `true`, which is displayed as number one.
* Space and newline are separators, and here do nothing.
* `v` concatenates the whole stack so far into a column vector. So for example `v` after `T` would concatenate the first two numbers into a column (and then the next number would be pushed). An initial `v` would produce an empty array.

At the end of the code, the stack is implicitly displayed, with the following rules:

* Each element or array in the stack is displayed on a different line.
* Column vectors are displayed with each element on a different line.
* The empty array causes no output.

So any permutation of the input characters produces `1` three times in different lines.

# Answer
> 6 votes
# Jelly, score ~~53~~ 101

```
¶ ¤$¥&+ABDFHNPQSUVX^_aborv|®²×ȧȯḄḅḌḞḢḤḷṀṂṚṛṠṢṪẠạị«»()kquƁƇƊƑƘⱮƝƤƬƲȤɓɗƒɦƙɱɲƥʠɼʂƭʋȥẸẈẒẎŻẹḥḳṇọụṿẉỵẓḋėġṅẏ

```

Using only characters that are part of Jelly's code-page.

Jelly has implicit input of `0`, and the first half (up to and including `ạị«»`) of the string of code above consists mostly of monadic (uppercase) and dyadic (lowercase and symbols) atoms that when given a zero or a list containing only one zero (or two such inputs in the case of dyads) return a zero or a list containing only one zero.

The exceptions are:

* The space: it is ignored (even though it is in the code-page).
* The pilcrow,  separates links (as does a line feed - but that is really the same byte), but no other bytes will reference the code before it anyway.
* the scarab, `¤`, instructs the parser to treat everything to it's left starting at a nilad (or constant) as a constant (and works as a first atom).
* the Dollar, `$`, instruct the parser to treat the two links to it's left as a monad (and, somewhat surprisingly, works as a first atom)
* the Yen, `¥`, similarly instructs the parser to treat the two links to it's left as a dyad.
* The recommended, `®`, recalls the value of the registry, initially `0` (it's counterpart copyright, `©`, breaks when used as the very first atom as it is arity is found from the arity of the link to it's left, which is not yet set).

The code from the parentheses, `(` and `)` and on, are currently unused code points, these all get parsed and each causes a new chain (much like a newline would, although they don't have the effect of creating callable links like a newline, but that's no problem here as nothing tries to do so).

# Answer
> 4 votes
# TI-Basic (83 series), 93 points (99 on a TI-84 Plus)

```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZθnπeiAnsrandgetKeyZXsclZYsclXsclYsclXminXmaxYminYmaxTminTmaxθminθmaxZXminZXmaxZYminZYmaxZθminZθmaxZTminZTmaxTblStartPlotStartZPlotStartnMaxZnMaxnMinZnMinΔTblTstepθstepZTstepZθstepΔXΔYXFactYFactTblInputNI%PVPMTFVP/YC/YPlotStepZPlotStepXresZXresTraceStep

```

All the digits, all the one-byte variables (including θ and *n*, the independent variables for polar and sequential graphing), the constants π, *e*, and *i*, some not-quite-variables (`Ans`, `rand`, and `getKey`), and 59 different window variables (all the ones that are guaranteed to be defined).

Implied multiplication guarantees that the result will be 0 when we take this in any order. If this is running on a fresh calculator, all the variables will be 0; even if not, `getKey` will be 0 because there's no time to press a key before the program returns a value.

On a TI-84 Plus or higher, we can get 6 more points by adding the tokens `getDate`, `getTime`, `startTmr`, `getDtFmt`, `getTmFmt`, `isClockOn`. The result will now always be `{0 0 0}` because `getDate` and `getTime` return lists of length 3 and the implied multiplication distributes over the elements.

I think these are all the possible tokens to use: any actual commands are prefix, infix, or postfix (meaning they won't work at the beginning or end of the program) and any other variables might be undefined (and cause an error when used).

# Answer
> 3 votes
# (non-competing) Brainf-ck, 63 bytes

Well, I don't know if this is considered cheating, but...

```
.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

```

The dot prints the current character (0x00) and the rest of the characters do nothing. This could technically be expanded infinitely, so please let me know if this is considered cheating.

# Answer
> 3 votes
## Haskell, 3 points

```
+ 1

```

No matter how rearranged this code always returns function which increments input. Examples of usage in repl:

```
>(+ 1) 1
2
>(1+ ) 1
2
>( +1) 1
2

```

# Answer
> 2 votes
# √ å ı ¥ ® Ï Ø ¿ , 128,234 (?) points

I arrived at 128,234 with help from @DestructibleLemon. This program uses all Unicode characters (128,237) except `o`,`O` and `ł`. Oddly enough, two of these are output commands.

Surely, though, no language could use all those characters, right? Well this language just ignores the commands it doesn't recognise. Problem solved.

This language will, by default, output the following:

```
===== OUTPUT =====

==================

```

which is non-nil, non-null, non-empty and non-error.

*Note: if this violates some unwritten rule, notify me in the comments and I'll change this. If you know my score (assuming this is allowed), also post in the comments.*

# Answer
> 1 votes
# ///, ~~1~~ 2 points

```
\_

```

Try it online!

I have no clue how to do it in any other Turing-complete language. Of course, there is HQ9, but that just feels cheaty.

1 byte thanks to @Martin Ender.

# Answer
> 1 votes
# J, 3 bytes

```
 1

```

The chars 1, space and newline will always print 1.

# Answer
> 1 votes
## Dots, 1,114,111 characters (if using unicode).

`<87 dots here> Every Unicode character except NUL and . here`

Explanation:

```
1                                           leading binary number
1010                                        010 increments the value under the pointer
1010111                                     111 prints out chr(1)

```

So the resulting binary string is `1010111`, which converted to decimal is 87, so we need 87 dots.

Every other character is a comment, so we use every character except a NUL, because Python3 stops reading the file then, and a dot, because dots aren't comments.

# Answer
> 0 votes
# Prelude, score 1,112,051

(When only considering the printable ASCII `[\t\n -~]`, the score is **84**. If we consider all Unicode code-points, the score is **1,112,051**.)

```
!
" #$    %&'+,-./0:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

(then append all characters `[\u{7f}-\u{10ffff}]` after it.)

Always print `0`.

---

Prelude is a parallel stack-based language, where the stack is pre-filled with infinite numbers of 0s.

* `+`: Pop two values (always 0), add them (0), and push to stack.
* `-`: Pop two values (always 0), subtract them (0), and push to stack.
* `#`: Pop a value and discard it.
* `!`: Pop a value and output it as a *number* (always 0) (spec says "character" but interpreter says "number"; either case, a byte is printed)
* `0`: Pushes 0.
* `^`, `v`, `V`: Pushes the top value of the previous/next parallel programs ("voices"), but the stacks of all "voices" are filled with 0, so they always push 0.
* other characters: no-op.

So there are only 13 characters we need to avoid:

* `(`, `)`: Unpaired parenthesis will cause error
* `1``9`: We only want to output 0.
* `?`: We don't want to input anything.
* `*`: Causes very complicated consistency check for the code before and after a line consisting of a lone `*`. So we need to either remove the new line or remove the `*`. The reference implementation uses Python 2's `.readline()` which a "new line" could mean `\r` or `\n`. So it is better to just remove the `*`.

# Answer
> 0 votes
# Deadfish, score 86

```
o.ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghjklmnpqrtuvwxyz?!|[]_-();'"*&^$#@!1234567890+=<>,/\:

```

If that's illegal, then there's also

```
o

```

(score 1)

---
Tags: restricted-source, code-bowling, radiation-hardening, pangram
---


title: All different functions

text:
# Question
Title: All different functions
For functions \\$f, g: \\{0,1\\}^n \rightarrow \\{0,1\\} \\$, we say \\$f \sim g\\$ if there's a permutation of \\$1,2,3,...,n\\$ called \\$i\_1,i\_2,i\_3,...,i\_n\\$ so that \\$f(x\_1,x\_2,x\_3,...,x\_n) = g(x\_{i\_1},x\_{i\_2},x\_{i\_3},...,x\_{i\_n})\\$. Therefore, all such functions are divided in several sets such that, for any two functions \\$f, g\\$ in a same set, \\$f \sim g\\$; for any two functions \\$f, g\\$ in different sets, \\$f \not\sim g\\$. (Equivalence relation) Given \\$n\\$, output these sets or one of each set.

Samples:

```
0 -> {0}, {1}
1 -> {0}, {1}, {a}, {!a}
2 -> {0}, {1}, {a, b}, {!a, !b}, {a & b}, {a | b}, {a & !b, b & !a}, {a | !b, b | !a}, {a ^ b}, {a ^ !b}, {!a & !b}, {!a | !b}

```

You can output the function as a possible expression(like what's done in the example, but should theoretically support \\$n\>26\\$), a table marking outputs for all possible inputs (truth table), or a set containing inputs that make output \\$1\\$.

Shortest code win.

# Answer
# , 62 bytes

```
f=:3 :'~.(2#~2^y)([:<@~.@/:~((i.@!A.i.)y)|:(y#2)$])@#:i.2^2^y'

```

Try it online!

-3 bytes for anonymous function (removing `f=:`)

For each boolean function (truth table), generate its equivalence class, then remove duplicates.
> 2 votes

---
Tags: code-golf
---


title: Determine the Widest Valley

text:
# Question
Title: Determine the Widest Valley
Imagine we get a slice of some mountainous region, this would result in a shape similar to this:

```
4                   _
3   _    _       __/ \
2  / \__/ \    _/     \_   /
1 /        \  /         \_/
0           \/
  12322223210012233343221112

```

As we can see, we can represent this (to a certain degree) with a sequence of integers.

For the purpose of this challenge we define a valley as a contiguous subsequence where the values initially are decreasing and from some point on they are increasing. More formally for a sequence \\$(a\_i)\_{i=1}^n\\$ a valley will be indices \\$1 \leq s \< r \< t \leq n\\$ for which the following holds:

* the valley's start and endpoint are the same: \\$a\_s = a\_t\\$
* the valley starts and ends once the region gets lower: \\$a\_s \> a\_{s+1} \land a\_{t-1} \< a\_t\\$
* the valley is not flat: \\$a\_s \neq a\_r \land a\_r \neq a\_t\\$
* the valley initially decreases: \\$\forall i \in \[s,r): a\_i \geq a\_{i+1}\\$
* the valley will at some point increase: \\$\forall j \in \[r,t): a\_j \leq a\_{j+1}\\$

Now we define the width of such a valley as the size of the indices \\$\[s,t\]\\$, ie. \\$t-s+1\\$.

## Challenge

Given a height-profile (sequence of non-negative integers), your task is to determine the width of the widest valley.

## Example

Given the height-profile `[1,2,3,2,2,2,2,3,2,1,0,0,1,2,2,3,3,3,4,3,2,2,1,1,1,2]`, we can visualize it as before:

```
4                   _
3   _    _       __/ \
2  / \__/ \    _/     \_   /
1 /        \  /         \_/
0           \/
  12322223210012233343221112
    aaaaaa             ccccc
         bbbbbbbbb

```

Note how the second valley `[3,2,1,0,0,1,2,2,3]` does not extend further to the right because the left-most point is \\$3\\$ and not \\$4\\$. Furthermore we don't add the remaining two \\$3\\$s because we require that the endpoint is higher up than the second-last point.

Therefore the width of the widest valley is \\$9\\$.

# Rules

* Input will be a sequence of non-negative (sorry Dutch people) integers
    + you can assume that there is always at least one valley
* Output will be the size of the widest valley as defined above

# Testcases

```
[4,0,4] -> 3
[1,0,1,0,1] -> 3
[1,0,2,0,1,2] -> 4
[13,13,13,2,2,1,0,1,14,2,13,14] -> 4
[1,2,3,2,2,2,2,3,2,1,0,0,1,2,2,3,3,3,4,3,2,2,1,1,1,2] -> 9
[3,2,0,1,0,0,1,3] -> 4

```

# Answer
# Python 2, ~~120~~ ~~115~~ ~~89~~ ~~87~~ ~~86~~ ~~152~~ 149 bytes

```
lambda a:max(r-l+1for l,v in e(a)for r,w in e(a)if max(a[l+1:r]+[0])<v==w*any(s(a[l:i])[::-1]+s(a[i:r])==a[l:r]for i,_ in e(a)));e=enumerate;s=sorted

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), ~~111~~ ~~108~~ ~~99~~ 97 bytes

```
a=>a.map(o=(p,x)=>a.some(P=q=>(~x?x<0?i?q<P:q>P&&i++:i=0:q>=p)||(o=o<--x|q==P|q-p?o:x,P=q,0)))|-o

```

Try it online!

### Commented

```
a =>                        // a[] = input array
  a.map(o =                 // initialize the output o to a non-numeric value
    (p, x) =>               // for each value p at position x in a[]:
    a.some(P =              //   initialize P to a non-numeric value
      q =>                  //   for each value q in a[]:
      (                     //     exit if something goes wrong:
        ~x ?                //       if x is not equal to -1:
          x < 0 ?           //         if x is negative:
            i ?             //           if we're in the increasing part:
              q < P         //             exit if q is less than P
            :               //           else:
              q > P && i++  //             increment i if q is greater than P
          :                 //         else:
            i = 0           //           initialize i to 0 (decreasing part)
        :                   //       else:
          q >= p            //         exit if q is greater than or equal to p
      ) || (                //     if we didn't exit:
        o =                 //       update the output o:
          o < --x |         //         decrement x; if o is less than x
          q == P |          //         or the last value is equal to the previous one
          q - p ?           //         or the last value is not equal to the first one
            o               //           leave o unchanged
          :                 //         else:
            x,              //           update o to x
        P = q,              //       update the previous value P to q
        0                   //       force this iteration to succeed
      )                     //
    )                       //   end of some()
  ) | -o                    // end of map(); return -o

```
> 3 votes

# Answer
# Jelly, 15 bytes

```
ẆµIṠḟ0ṢƑaMIḢ)Ṁ‘

```

**Try it online!**

Or see a test-suite (added two more test cases which I previously failed to fulfil).

### How?

```
ẆµIṠḟ0ṢƑaMIḢ)Ṁ‘ - Link: list of integers
Ẇ               - all contiguous substrings
 µ          )   - for each substring, X:
  I             -   deltas
   Ṡ            -   sign (-ve:-1, 0:0, +ve:1)
    ḟ0          -   filter out zeros
       Ƒ        -   is invariant under:
      Ṣ         -     sort
         M      -   get maximal indices of X
        a       -   (vectorising) logical AND
          I     -   deltas
           Ḣ    -   head
             Ṁ  - maximum
              ‘ - increment

```
> 3 votes

# Answer
# Japt, 31 bytes

```
¡ãYÄÃrc k_ò< Åd_äa x}Ã®bZvÃrÔ+2

```

Try it online!

Saved a 10 bytes by taking inspiration from Zgarb's Husk answer. I still think this can be improved, but I haven't found it yet.

Explanation:

```
¡ãYÄÃrc                            Get all segments
        k_           Ã             Remove ones where:
          ò<                        A non-increasing sub-segment
             Å                      Other than the first one
              d_äa x}               Has different heights
                      ®   Ã        For each remaining segment:
                       bZv          Get the second index of the first character
                           rÔ      Maximum
                             +2    Increase by 2

```
> 1 votes

# Answer
# Retina 0.8.2, 77 bytes

```
\d+
$*
M&!`\b(1+),((?!\1)(?!1+\2)1*,)+((?!\1)1*(?(3)\3|\2))*\1\b
1

O^`
\G,|$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
M&!`

```

List, rather than counting, overlapping matches.

```
\b(1+),

```

The valley's start is captured into `\1`. This must then not match again until the end. Since we don't capture the comma, this also prevents higher values from matching.

```
((?!\1)(?!1+\2)1*,)+

```

Match the decreasing values. The `(?!1+\2)` prevents the any pass through the loop from being greater than the previous. (The first time through `\2` isn't set so it fails to match trivially.) The capture includes the trailing comma as that's golfier.

```
((?!\1)1*(?(3)\3|\2))*

```

Match the increasing values. This time `((?3)\3|\2)` means that each match is required to be at least as long as the previous value, or the last decreasing capture the first time through the loop.

```
\1\b

```

Finally the end of the valley must be the same height as the start.

```
1

```

Delete the heights, leaving the commas. (This is slightly easier than counting the heights as some of them might be zero.)

```
O^`

```

Sort in reverse order i.e. most commas first.

```
\G,|$

```

Count the number of commas on the first line, plus one.
> 1 votes

# Answer
# Husk, 13 bytes

```
→▲mΓ€fȯΛEtġ≤Q

```

Try it online!

## Explanation

I use a similar algorithm as Jonathan Allan.

```
→▲mΓ€fȯΛEtġ≤Q  Input is a list, say [3,1,0,1,1,0,2,3]
            Q  Nonempty slices: [[3],[1],[3,1],[0],...,[3,1,0,1,1,0,2,3]]
     f         Keep those that satisfy this:
                Argument is a slice, say [3,1,0,1,1,0,2]
          ġ≤    Cut into non-increasing pieces: [[3,1,0],[1,1,0],[2]]
         t      Drop first piece: [[1,1,0],[2]]
      ȯΛ        Each remaining piece
        E       has all elements equal: false, [1,1,0] has different elements
  m            Map over remaining slices:
                Argument is a slice, say [1,0,1,1]
   Γ            Break into head 1 and tail [0,1,1]
    €           Index of first occurrence of head in tail: 2
 ▲             Maximum: 2
→              Increment: 3

```
> 1 votes

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


title: Volumes of ASCII boxes

text:
# Question
Title: Volumes of ASCII boxes
## Introduction

In this challenge, you are given as input the ASCII representation of the net (unfolded surface) of a rectangular cuboid (3D box). The format is this:

```
....+--+.......
....|##|.......
....|##|.......
....|##|.......
+---+--+---+--+
|###|##|###|##|
+---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......

```

Each face of the cuboid is a rectangle of `#`s surrounded by `+-|`-characters. The outside of the net is filled with `.`s. The net will always have the same orientation: there's a middle face surrounded by its four neighboring faces, and the counterpart of the middle face is at the right border of the input. The input is padded with `.`s to a rectangular shape and will not contain extra rows or columns of `.`s.

## The task

Your task is to take as input a diagram as above, and compute the volume of the cuboid that it represents, which is just the product of its height, width and depth. You can take the input as a newline-delimited string or an array of strings.

The length of each edge is the distance between the `+`-characters at its two ends. For example, the horizontal edge `+--+` has length 3, and the vertical edge

```
+
|
|
|
+

```

has length 4. The minimum length of an edge is 1. The example cuboid above has volume 2\*3\*4 = 24.

## Rules and scoring

You can write a full program or a function, and the lowest byte count wins.

## Test cases

```
.++..
+++++
+++++
.++..
1

...++....
...||....
...||....
+--++--++
+--++--++
...||....
...||....
...++....
3

..+-+....
..|#|....
+-+-+-+-+
|#|#|#|#|
|#|#|#|#|
+-+-+-+-+
..|#|....
..+-+....
12

.+---+.....
++---++---+
||###||###|
||###||###|
||###||###|
++---++---+
.+---+.....
16

....++.....
....||.....
....||.....
....||.....
+---++---++
|###||###||
|###||###||
|###||###||
+---++---++
....||.....
....||.....
....||.....
....++.....
16

...+--+......
...|##|......
...|##|......
+--+--+--+--+
|##|##|##|##|
+--+--+--+--+
...|##|......
...|##|......
...+--+......
18

....+--+.......
....|##|.......
....|##|.......
....|##|.......
+---+--+---+--+
|###|##|###|##|
+---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......
24

....+-----+..........
....|#####|..........
....|#####|..........
....|#####|..........
+---+-----+---+-----+
|###|#####|###|#####|
|###|#####|###|#####|
|###|#####|###|#####|
|###|#####|###|#####|
+---+-----+---+-----+
....|#####|..........
....|#####|..........
....|#####|..........
....+-----+..........
120

```

# Answer
## Retina, ~~29~~ 28 bytes

```
T`.p`xy`\G\..+¶
xy

¶\|
$`
y

```

Try it online!

There's a *lot* of ways to approach this in Retina, depending on which area you want to multiply with which side, so I'm not sure how optimal this is, but it's actually already a lot shorter than I thought it would be.

I've currently got two other solutions at the same byte count which seem a bit more golfable than the above approach:

```
\G\..+¶

¶\|
$'¶
G`\.
T`.|+

```

```
¶\||\+¶\.\D+
$'¶
G`\.
T`.|+

```

Although in these I could save a byte each if I assume that the input ends with a trailing linefeed, but I'd rather not have to rely on that.

And another one, still at 28 bytes (this one actually multiplies three sides instead of multiplying one area by a side):

```
\G\.
x
-(?<=^.+)
$`
¶\|
$`
x

```

### Explanation

The main idea is to multiply the area of the face on top by the length of the vertical side that touches the length border of the input.

I'll use the following input as an example (it has side lengths 2, 3 and 4, so an area of 24):

```
...+---+.......
...|###|.......
...|###|.......
+--+---+--+---+
|##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

```

**Stage 1: Transliterate**

```
T`.p`xy`\G\..+¶

```

The regex `\G\..+¶` matches a line which starts with `.` and is immediately adjacent to the previous line. So this matches all the lines that contain the top face. The stage itself turns `.` into `x` and all other characters (any of `|+-#`) into `y`. This gives us the following result:

```
xxxyyyyyxxxxxxx
xxxyyyyyxxxxxxx
xxxyyyyyxxxxxxx
+--+---+--+---+
|##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

```

This has one more column of `y` than we need to represent the area of the top face. We fix this with the next stage.

**Stage 2: Replace**

```
xy

```

So we match a `y` that is preceded by an `x` (which is exactly one of them per line) and remove them both from the string. We get this:

```
xxyyyyxxxxxxx
xxyyyyxxxxxxx
xxyyyyxxxxxxx
+--+---+--+---+
|##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

```

So now we've got the area of the top face represented by the number of `y`s.

**Stage 3: Replace**

```
¶\|
$`

```

Our goal here is to multiply this area `A` by the missing side length, which is the number of `|` at the beginning of a line plus 1. However, it's actually easier to multiply by a number `n+1` because we've already got one copy of `A` in the string. If we replace `n` things with `A`, we end up with `n+1` copies of `A`. This makes things a lot easier for us.

So we simply replace any `|` immediately after a linefeed with everything in front of the match. This mangles the string quite a lot and makes it a fair bit larger than we need, but the number of `y`s ends up being the result we're looking for:

```
xxyyyyxxxxxxx
xxyyyyxxxxxxx
xxyyyyxxxxxxx
+--+---+--+---+xxyyyyxxxxxxx
xxyyyyxxxxxxx
xxyyyyxxxxxxx
+--+---+--+---+##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

```

**Stage 4: Match**

```
y

```

All that's left is to count the number of `y`s, which is printed as a decimal number at the end.
> 25 votes

# Answer
## Python 2, 57 bytes

```
lambda l:l[0].find('+')*~l[0].count('-')*~`l`.count("'|")

```

A function that takes in a list of strings.

Determines the 3 dimensions separately:

`l[0].find('+')`
The index of the first `+` in the first row.

`-~l[0].count('-')`
The number of `-` signs in the first row.

`~`l`.count("'|")`
The number of rows starting with `|` symbol, via the string representation of the list having a quote symbol before it.

---

**62 bytes:**

```
def f(l):a=l[0].find('+');print(len(l[0])/2-a)*(len(l)-a+~a)*a

```

A function that takes in a list of strings and prints the result.

Finds one dimension `a` as the index of `+` in the first row. The other two dimensions are inferred from it and the width and height of the input rectangle.

A 63-byte alternative, finding the dimensions separately:

```
lambda l:l[0].find('+')*~l[0].count('-')*~zip(*l)[0].count('|')

```
> 15 votes

# Answer
# Bash + coreutils, ~~83~~, 77 bytes

EDITS:

* Saved 6 bytes, by using "Here String" and optimizing regexp a bit

**Golfed**

```
bc<<<`sed -rn '1{s/(.+)[^\.]*\1/(0\1)*(0/
s/\./+1/gp;a)*(-1
}
/^[+|]/a+1
'`\)

```

**Explained**

Transform with *sed*:

```
....+--+....... => (0+1+1+1+1)*(0+1+1+1 )*(-2 +1
. =>()
. =>()
. =>()
. =>()
+ => +1
| => +1
+ => +1
. =>()
. =>()
. =>()
. =>()

```

Get rid of newlines using backticks, append )

```
=> (0+1+1+1+1)*(0+1+1+1 )*(-2 +1 +1 +1 +1)

```

Feed resulting expression to *bc*

```
=> 24

```

**Test**

```
./box <<EOF
.++..
+++++
+++++
.++..
EOF

1

./box <<EOF
...++....
...||....
...||....
+--++--++
+--++--++
...||....
...||....
...++....
EOF

3

./box <<EOF
....+--+.......
....|##|.......
....|##|.......
....|##|.......
+---+--+---+--+
|###|##|###|##|
+---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......
EOF

24

```

**Try it online !** (uses bash arithmetic expansion, instead of *bc*, as the latter is not available)
> 11 votes

# Answer
# Snails, 19 bytes

```
AM
=~d^.+\+.+l.+^.2

```

<sub> Try it online. </sub>

The idea is that we start somewhere on the rightmost edge in the net, and then travel to somewhere in the bottommost face. The length of the edge and the area of the face are multiplied by the mechanism of counting all matching paths.

```
AM   ,, A -> count all matching paths
     ,, M -> first char matched is the one in the current direction
     ,,      from the starting location, rather than directly on it
=~          ,, check that we are on the right edge of the grid
d ^.+ \+    ,, go down, matching one or more non-'.' characters, then a '+'
.+          ,, go down one or more times
l .+        ,, go left one or more times
^. 2        ,, match two further characters which aren't '.' to the left

```
> 10 votes

# Answer
# JavaScript (ES6), 67 ~~91~~

```
s=>(a=~-s.search`
`/2-(b=s.indexOf`+`))*b*(s.split`
`.length-1-2*b)

```

**Test**

```
F=
s=>(a=~-s.search`
`/2-(b=s.indexOf`+`))*b*(s.split`
`.length-1-2*b)

out=x=>O.textContent+=x+'\n\n'

;`.++..
+++++
+++++
.++..
1

...++....
...||....
...||....
+--++--++
+--++--++
...||....
...||....
...++....
3

..+-+....
..|#|....
+-+-+-+-+
|#|#|#|#|
|#|#|#|#|
+-+-+-+-+
..|#|....
..+-+....
12

.+---+.....
++---++---+
||###||###|
||###||###|
||###||###|
++---++---+
.+---+.....
16

....++.....
....||.....
....||.....
....||.....
+---++---++
|###||###||
|###||###||
|###||###||
+---++---++
....||.....
....||.....
....||.....
....++.....
16

...+--+......
...|##|......
...|##|......
+--+--+--+--+
|##|##|##|##|
+--+--+--+--+
...|##|......
...|##|......
...+--+......
18

....+--+.......
....|##|.......
....|##|.......
....|##|.......
+---+--+---+--+
|###|##|###|##|
+---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......
24

....+-----+..........
....|#####|..........
....|#####|..........
....|#####|..........
+---+-----+---+-----+
|###|#####|###|#####|
|###|#####|###|#####|
|###|#####|###|#####|
|###|#####|###|#####|
+---+-----+---+-----+
....|#####|..........
....|#####|..........
....|#####|..........
....+-----+..........
120`
.split('\n\n').forEach(t=>{
  t=t.split('\n')
  k=+t.pop()
  t=t.join('\n')
  v=F(t)
  out(v+' '+k +' '+(v==k?'OK':'KO')+'\n'+t)
})
```

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

# Answer
# Ruby, 44

Works on a similar principle to other answers: find the first `+` to find the depth, find the next `.` after the `+` to find the width, and count the number of `|` at end of line and add 1 to find height.

```
->s{(s=~/\+/)*($'=~/\./)*s.split("|
").size}

```

**ungolfed in test program**

```
f=->s{(s=~/\+/)*    # index of first match of /\+/ in s
($'=~/\./)*         # $' is a special variable, contains string to right of last match. index of /\./ in $'
s.split("|
").size}            # split the string at |\n to form an array and count the members

puts f[".++..
+++++
+++++
.++.."]

puts f["...++....
...||....
...||....
+--++--++
+--++--++
...||....
...||....
...++...."]

#etc.

```
> 3 votes

# Answer
# 05AB1E, 21 bytes

Let `W` and `H` be respectively the width and the height of the input - not the box. Then, the box dimensions `A`, `B` and `C` follow these rules:

```
W = 2(A+C)+1
H = B+2C+1

```

The following figure shows what `A`, `B` and `C` are, in terms of edge names:

```
....AAAA.......
....|##|.......
....|##|.......
....|##|.......
B---+--CCCCC--+
B###|##|###|##|
B---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......

```

Hence the above formulas. This program computes `A`, deduces the values of `B` and `C` and finally computes their product.

```
S'.ÊO<D¹g<;-(D·|g-()P

S'.Ê                  From each character of the first line, yield 0 if it is '.' or 1 otherwise. The result is stored in an array
    O<D               A = sum(array) - 1
       ¹g<;-(D        C = (W-1)/2 - A
              ·|g-(   B = H-1-2*C
                   )  Yield [A,C,B]
                    P Take the product and implicitly display it

```

Try it online!

# Former version - Different approach - 26 bytes

```
|vyS'.Ê})¬O<sø¬O<s€O¬Ê1k)P

|                          Take the input as an array of lines (strings)
 vy                        For each line
   S'.Ê                    For each character in the line, yield 0 if it is '.' or 1 otherwise
       }                   End For
        )                  Wrap the results as an array
         ¬O<               A = sum(first_line) - 1
            sø             Transpose the box pattern
              ¬O<          B = sum(first_line) - 1 ; since the pattern is transposed, it corresponds to the first column
                 s€O       Sum every line from the transposed pattern
                    ¬Ê1k   C = index of the first line that has a different sum from the first line
                        )  Yield [A, B, C]
                         P Take the product A*B*C and implicitly display it

```
> 3 votes

# Answer
# Haskell, ~~64~~ 56 bytes

```
f(x:r)=sum$fst(span(>'+')x)>>[1|'|':_<-"|":r,'-'<-'-':x]

```

Try it online!

### Explanation

The input is expected to be a list of strings for each line, so in `f` the parameter `x` is the first line and `r` a list of the remaining lines.

1. `fst(span(>'+')x)` returns the `.`-prefix of the first line as a string, so `length(fst(span(>'+')x))` is the first dimension `d1`.
2. A list comprehension can act as filter, e.g. `['-' | '-' <- x]` returns a string of all `-` in the first line, so `1 + length['-' | '-' <- x]` yields the second dimension `d2`.
3. Analogously the number of `|` in the first row can be counted, so `1 + length['|' | '|':_ <- r]` is the third dimension `d3`.

The list comprehensions of 2. and 3. can be shortened to `1+sum[1|'-'<-x]` and `1+sum[1|'|':_<-r]` by building a list of ones for each occurrence of '-' or '|' and then taking the sum. We can further put the outer `1+` into the list comprehension by appending `-` to `x` and `"|"` to `r` to yield `sum[1|'-'<-'-':x]` and `sum[1|'|':_<-"|":r]`. Now we can combine both list comprehensions by putting both predicates in the same comprehension: `sum[1|'|':_<-"|":r,'-'<-'-':x]` Conveniently this computes exactly the product of the two dimensions because for lists `F` and `G` the following list comprehension is the Cartesian product `F x G =[(a,b)|a<-F,b<-G]`.

Finally, instead of multiplying 1. with the combination of 2. and 3. we can make use of the `>>` operator on lists: `F>>G` repeats `G` `length F` times and concatenates the result. So `fst(span(>'+')x)>>[1|'|':_<-"|":r,'-'<-'-':x]` repeats the list of `d2*d3` ones `d1` times, yielding a list of `d1*d2*d3` ones which are then summed up to get the volume.
> 2 votes

# Answer
# Befunge 93, 56 bytes

```
~2%#^_1+
  @.*+<
`"z"~<|:`~0+
5*\`#^_\1>*\~7
%2~\<\+1_^#

```

Try it Online!

### Explanation:

The volume of the box can be calculated by multiplying the number of `.`s on the first line before any other characters, by the number of `+` and `-`s on the first line - 1, and the number of lines that start with a `|` \+ 1.

```
~2%#^_1+         Uses the ASCII value % 2 of a character to count the .s

%2~\<\+1_^#      IP wraps around to the bottom. Counts the non . chars
                 Works because ("+" % 2) == ("-" % 2) == 1

5*\`#^_\1>*\~7   Multiplies the previous 2 results and cycles through
                 characters until it hits a newline or EOF

`"z"~<|:`~0+     Adds 1 to the 3rd dimension if the following char is a "|"
                 Also checks for EOF; If there is more input, goes back to
                 previous line. Otherwise, goes to the last line

  @.*+<          Adds 1 to the 3rd dimension, multiplies it to the rest,
                 prints the volume, and ends the program

```

I had to move the IP up lines instead of down in order to use the vertical if in the 3rd line. If the IP was going down lines, the vertical if would force the top of the stack to be 1 when hitting the following horizontal if, sending it in the wrong direction.
> 2 votes

# Answer
# Java 8, ~~185~~ 129 bytes

thanks to Zgarb for -56 bytes

golfed:

```
int g(String[]i){int h=0;for(String k:i){if(k.charAt(0)=='.')h++;else break;}return((i[0].length()-2*h-1)/2)*(i.length-2*h-1)*h;}

```

ungolfed:

```
int g(String[] i) {
    int h = 0;
    for (String k : i) {
        if (k.charAt(0) == '.') h++;
        else break;
    }
    return ((i[0].length()-2*h-1)/2)*(i.length-2*h-1)*h;
}

```

## Explanation

`a*b*h = ((length_of_line-2*h-1)/2)*(number_of_lines-2*h-1)*h`

where `a` and `b` are the dimensions of the base and `h` is the height. You can find `h` by counting the first `h` lines where you begin with a `.`.
> 1 votes

# Answer
# Java, 112 bytes

```
int v(String[]s){int a=s[0].lastIndexOf('+')-s[0].indexOf('+'),b=s[0].length()/2-a;return a*b*(s.length-2*b-1);}

```

Expanded:

```
int v(String[] s)
{
  // length of the edge in the first line
  int a = s[0].lastIndexOf('+') - s[0].indexOf('+');
  // length of the second edge
  // int b = s[0].length() - 2 * a - 1; <-- multiplied by 2
  int b = s[0].length()/2 - a; // <-- hack, length is always odd
  // length of the third edge in ()
  // volume
  return a * b * (s.length - 2 * b - 1);
} // end method v

```
> 1 votes

# Answer
# Powershell, ~~68~~ 67 bytes

```
($c="$args"|% i*f +)*($args[0].Length/2-.5-$c)*($args.Count-1-2*$c)

```

Note: `"$args"|% i*f +` is shortcut for `"$args".indexOf('+')`

## Explanation

Good explanation took from the Osable's answer:

Let `W` and `H` be respectively the width and the height of the input - not the box. Then, the box dimensions `A`, `B` and `C` follow these rules:

```
W = 2(A+C)+1
H = B+2C+1

```

The following figure shows what `A`, `B` and `C` are, in terms of edge names:

```
CCCCAAAA.......
....|##|.......
....|##|.......
....|##|.......
B---+--+---+--+
B###|##|###|##|
B---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......

```

And `C` is position of the first `+` in the first line of the input.

Test script:

```
$f = {

($c="$args"|% i*f +)*($args[0].Length/2-.5-$c)*($args.Count-1-2*$c)

}

@(

,(1, ".++..",
     "+++++",
     "+++++",
     ".++..")

,(3,"...++....",
    "...||....",
    "...||....",
    "+--++--++",
    "+--++--++",
    "...||....",
    "...||....",
    "...++....")

,(12,"..+-+....",
     "..|#|....",
     "+-+-+-+-+",
     "|#|#|#|#|",
     "|#|#|#|#|",
     "+-+-+-+-+",
     "..|#|....",
     "..+-+....")

,(16,".+---+.....",
     "++---++---+",
     "||###||###|",
     "||###||###|",
     "||###||###|",
     "++---++---+",
     ".+---+.....")

,(16,"....++.....",
     "....||.....",
     "....||.....",
     "....||.....",
     "+---++---++",
     "|###||###||",
     "|###||###||",
     "|###||###||",
     "+---++---++",
     "....||.....",
     "....||.....",
     "....||.....",
     "....++.....")

,(18,"...+--+......",
     "...|##|......",
     "...|##|......",
     "+--+--+--+--+",
     "|##|##|##|##|",
     "+--+--+--+--+",
     "...|##|......",
     "...|##|......",
     "...+--+......")

,(24,"....+--+.......",
     "....|##|.......",
     "....|##|.......",
     "....|##|.......",
     "+---+--+---+--+",
     "|###|##|###|##|",
     "+---+--+---+--+",
     "....|##|.......",
     "....|##|.......",
     "....|##|.......",
     "....+--+.......")

,(120,"....+-----+..........",
      "....|#####|..........",
      "....|#####|..........",
      "....|#####|..........",
      "+---+-----+---+-----+",
      "|###|#####|###|#####|",
      "|###|#####|###|#####|",
      "|###|#####|###|#####|",
      "|###|#####|###|#####|",
      "+---+-----+---+-----+",
      "....|#####|..........",
      "....|#####|..........",
      "....|#####|..........",
      "....+-----+..........")

) | % {
    $expected,$s = $_
    $result = &$f @s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: 1
True: 3
True: 12
True: 16
True: 16
True: 18
True: 24
True: 120

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 64 bytes

```
(2(x=#@"
")-(y=#@"|")-9)((9-5x+y)^2-9#@".")/54&@*CharacterCounts

```

Try it online!

Uses the number of `.`, `|`, and `\n` characters in the input to solve for the volume. It looks stupid because there's an actual new line in place of `\n`.

If `A`, `B`, and `C` are the sides, then `. = 2C(A+2C)`, `| = 5B+4C-9`, and `\n = B+2C`, so we can solve for the volume `ABC` in terms of these three character counts.
> 0 votes

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