title: What color is this?

text:
# Question
Title: What color is this?
You are to golf a program that will take a filename as input and you must output what color the file is.

The file will have any one of these extensions but your program only needs to support one. Please say which one in your answer.

* `.jpg`
* `.png`
* `.svg`
* `.gif`
* `.bmp`

And now to the classic layout.

# Input

A filename with one of the above extensions.

You may also take an image object or already encoded image instead.

# Output

The only color in that file as a 6 digit hex code with an *optional* leading `#` e.g. `#000000` is black.

You may also output a list/tuple/string containing the decimal or hex values of the RGB color, with a clear, non-numeric delimiter e.g.  `,` `|` etc

You may not output the transparency.

If the file isn't all one color, you must output a falsy value that isn't `#000000` and terminate **without** printing anything to `STDERR`. This is so that you can't simply open the file and get the RGB value of the first pixel.

# Rules

* The hex code only needs to be outputted if the file is all one color.
* The file will be `500x500` pixels
* The pixels will all have 0% transparency.
* This is so shortest code wins!

# Examples

# Answer
> 6 votes
# MATL, ~~15~~ 12 bytes

```
Yi6Bed~?2MYm

```

Tested with the ".png" images given in the challenge. It probably works with other extensions too. Input can be a filename or a URL of the image.

Output is R, G, B decimal values separated by spaces, or the empty string (which is falsy) if there are more than one color.

Example with first and last test cases:

### Explanation

```
Yi      % Implicitly input filename. Read image as an M×N×3 array
6B      % Push [true true false] (6 in binary)
e       % Reshape. This collapses firsts two dimensions. Gives an (M*N)×3 array
d       % Consecutive diferences down each column. Gives an an (M*N-1)×3 array
~?      % If all those differences are zero (this means there is a single color)
  2M    %   Push the (M*N)×3 array again
  Ym    %   Mean of each column
        % Implicit end
        % Implicitly display

```

# Answer
> 5 votes
# Bash + core-utils + Imagemagick, 60

```
a=(`convert $1 txt:|sort -uk3`)
((${#a[@]}-9))||echo ${a[2]}

```

Outputs the colour if there is one colour and nothing if there is more than one colour.

* `convert $1 txt:` reads the input file and outputs as a text file, specifically in this format:

```
# ImageMagick pixel enumeration: 500,500,255,srgba
0,0: (245,236,236,1)  #F5ECEC  srgba(245,236,236,1)
1,0: (245,236,236,1)  #F5ECEC  srgba(245,236,236,1)
2,0: (245,236,236,1)  #F5ECEC  srgba(245,236,236,1)
3,0: (245,235,235,1)  #F5EBEB  srgba(245,235,235,1)
4,0: (245,235,235,1)  #F5EBEB  srgba(245,235,235,1)

```
* `sort -uk3` uniquely sorts this by the third column. This output is assigned to an array `a`
* `((${#a[@]}-9))` tests if the array does NOT have length 9
* if the array does NOT NOT have length 9 (i.e. it does have length 9), then output element 2 (0-based) which will be the unique colour.

# Answer
> 4 votes
# JavaScript (ES6) + HTML, ~~315~~ ~~289~~ ~~243~~ ~~218~~ ~~217~~ ~~215~~ ~~211~~ ~~210~~ 208 bytes

~~Checking that all pixels were identical added a *lot* of bytes.~~ Down to it not being much bigger than when I was just checking the colour of the first pixel - happy with that :)

Takes the URL (absolute, relative, data or anything that can be used as the `src` of an `img`) of the image file as input. Outputs the RGB colour as a comma separated string or `0` for falsey. Tested with PNG files but should work with JPG & GIF too.

```
u=>(a=[...Array(c.width=c.height=500)]).map((_,x)=>a.map((_,y)=>(v=""+[(d=g.getImageData(x,y,1,1).data)[0],d[1],d[2]],h=x&y?v!=h?0:h:v)),i.src=u,(g=c.getContext`2d`).drawImage(i,0,0))&&h

```

```
<img id=i><canvas id=c

```

---

## Try it

Requires the addition of a closing `>` on the `canvas` element in order to work in a Snippet. As pulling images in from external sources would cause an error to be thrown, the following will instead take Base-64 data URLs as input. Uncomment the last line to test for different colours using an image consisting of the 4 test colours.

```
f=
u=>(a=[...Array(c.width=c.height=500)]).map((_,x)=>a.map((_,y)=>(v=""+[(d=g.getImageData(x,y,1,1).data)[0],d[1],d[2]],h=x&y?v!=h?0:h:v)),i.src=u,(g=c.getContext`2d`).drawImage(i,0,0))&&h
console.log(f("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQMAAADxGE3JAAAAA1BMVEUWwpMvG5UqAAAANUlEQVR42u3BMQEAAADCIPun9lkMYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5fQAAASJ0bysAAAAASUVORK5CYII"))
//console.log(f("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AgMAAAC2uDcZAAAADFBMVEWLFsIWwpOVkJCE8Az9F2TyAAABB0lEQVR42uzNIQEAMAwDsEk8ucmTS9xElAwkBlI3cipit9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91uX72/yO+I3W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdPhu1fdT2UdtHbR+1fdT2UdsHs+0AqVGfBnNZ7+UAAAAASUVORK5CYII"))
```

```
<img id=i><canvas id=c>
```

# Answer
> 3 votes
# Python 2, 80 bytes

```
from PIL import Image
i=Image.open(input()).getcolors(1)
print i and i[0][1][:3]

```

PIL.Image has a getcolors function which returns `None` if the number of colors is bigger than the parameter and returns a histogram of the colors in a `[(pixels, (r,g,b,a)), ...]` structure.

# Answer
> 3 votes
## Mathematica, ~~55~~ 51 Bytes

-4 thanks to CalculatorFeline

+0 for refactoring into full function.

Using Mathematica image object as input - `Import["filename.png"]`.

```
If[Length@#==1,#,0]&@Union[Join@@ImageData@#]&

```

Returns 0 if not all one color. Outputs the decimal value of the color if just one.

Explanation:

```
                                 ImageData@# & - Convert input into 2D array of RGB values
                           Join@@              - Join the array into 1D array f RGB values
                     Union[                 ]  - Union all the RGB values
   Length@#        &@                          - Find length of the union of arrays
If[        ==1,#,0]                            - Check if its 1, return it if true, return 0 if not

```

# Answer
> 2 votes
# Java 8+, ~~331~~ ~~165~~ 119 bytes

```
i->{Integer j=i.getRGB(0,0),k=500,l;for(;k-->0;)for(l=500;l-->0;)if(i.getRGB(k,l)!=j)return"";return j.toHexString(j);}

```

-a lot of bytes thanks to @LethalCoder for updating me on a rule change that allowed for a lot of golfing
-46 bytes thanks to @KevinCruijssen and fixed typo

# Answer
> 1 votes
# C#, ~~163~~ ~~128~~ 125 bytes

```
b=>{var c=b.GetPixel(0,0);for(int w=500,h;w-->0;)for(h=500;h-->0;)if(b.GetPixel(w,h)!=c)return"";return c.R+" "+c.G+" "+c.B;}

```

*Saved 3 bytes thanks to @Kevin Cruijssen.*

If we didn't have to have the additional check for the image being the same colours this is only 55 bytes:

```
b=>{var c=b.GetPixel(0,0);return c.R+" "+c.G+" "+c.B;};

```

# Answer
> 1 votes
# Python 2, ~~123~~ 85 bytes

```
from PIL import Image
c=Image.open(input()).getdata()
print len(set(c))<2and c[0][:3]

```

# Answer
> 1 votes
# C, ~~224~~ 205 bytes

```
m[3],i;
main(c,v)char**v;{
void*s=fopen(v[1],"r");
for(;i<54;i++)getc(s);
m[2]=getc(s);m[1]=getc(s);*m=getc(s);
for(i=0;i<500*500;i++)if((c=getc(s))!=m[i%3]&&~c)exit(puts("0"));
printf("%d,%d,%d",*m,m[1],m[2]);}

```

Takes a 500x500 bitmap as a command-line argument. Prints the RGB of the file, e.g. `255,255,255`, or `0` if the file is not constant. Probably crashes badly if no file is provided.

Interesting points to note:

* Uses `void*` in the place of `FILE*` to avoid including `<stdio.h>`
* Uses a simple `for` loop with `i%3` to determine if all bytes are the same
* Can be *very* golfed, I golfed 50 bytes while writing this answer
* BMP stores colors as BGR so it more/less reads backwards

# Answer
> 0 votes
## Mathematica, 112 bytes

image

> i=Import@"c:\a.png";

```
If[Length@DominantColors@i==1,"#"<>StringPadLeft[IntegerString[Most@PixelValue[i,{1,1},"Byte"],16],2,"0"],False]

```

# Answer
> 0 votes
# Bash + ImageMagick, 100 bytes

```
i=$(expr `identify -format "%k" $1` = 1)&&convert $1 -format "%c" histogram:info:-|grep -o "#......"

```

Tested with .png, should work with the other formats as well. The output for a polychromatic image is simply an empty string.

# Answer
> 0 votes
# JavaScript + HTML, 143 + 23 = 166 bytes

```
u=>(i.src=u,s=C.width=C.height=500,c=C.getContext`2d`,c.drawImage(i,0,0),d=c.getImageData(0,0,s,s).data,!d.some((n,i)=>n-d[i%4])&&d.slice(0,3))

```

```
<img id=i><canvas id=C>

```

### Try it:

```
f=
u=>(i.src=u,s=C.width=C.height=500,c=C.getContext`2d`,c.drawImage(i,0,0),d=c.getImageData(0,0,s,s).data,!d.some((n,i)=>n-d[i%4])&&d.slice(0,3))

console.log(
    f('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQMAAADxGE3JAAAAA1BMVEUWwpMvG5UqAAAANUlEQVR42u3BMQEAAADCIPun9lkMYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5fQAAASJ0bysAAAAASUVORK5CYII'),
    f('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AgMAAAC2uDcZAAAADFBMVEWLFsIWwpOVkJCE8Az9F2TyAAABB0lEQVR42uzNIQEAMAwDsEk8ucmTS9xElAwkBlI3cipit9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91uX72/yO+I3W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdPhu1fdT2UdtHbR+1fdT2UdsHs+0AqVGfBnNZ7+UAAAAASUVORK5CYII')
)
```

```
<img id=i><canvas id=C>
```

Less golfed:

```
u => {
    i.src = u
    s = C.width = C.height = 500
    c = C.getContext('2d')
    c.drawImage(i, 0, 0)
    d = c.getImageData(0, 0, s, s).data
    return d.every((n,i) => n == d[i % 4]) && d.slice(0,3)
}

```

# Answer
> 0 votes
# PowerShell, 79 bytes

```
param($b)if(!($c=499..0*500|%{$b|% G*l $_ $y;$y+=!$_}|gu).Rank){$c.R;$c.G;$c.B}

```

Less golfed test script:

```
$f = {

    param($b)
    $c=499..0*500|%{$b.GetPixel($_,$y);$y+=!$_}|gu
    if(!$c.Rank){
        $c.R;$c.G;$c.B
    }

}

@(
    ,("22 194 147", "https://cdn.pbrd.co/images/8bawQk5kM.png")
    ,("139 22 194", "https://cdn.pbrd.co/images/8b9foR0H6.png")
    ,("149 144 144","https://cdn.pbrd.co/images/8baglmIE8.png")
    ,("132 240 12", "https://cdn.pbrd.co/images/8b9Uhhovn.png")
    ,("",           "https://cdn.pbrd.co/images/8bb4DeKx3.png")

) | % {
    $expected,$s = $_

    $binData = [System.Net.WebClient]::new().DownloadData($s)
    $memoryStream = [System.IO.MemoryStream]::new($binData)
    $bitmap = [System.Drawing.Bitmap]::FromStream($memoryStream)

    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    $result = &$f $bitmap
    "$("$result"-eq$expected): $($sw.Elapsed): $result"
}

```
* *Note 1*: expression `499..0*500` means: repeat 500 times an range from 499 downto 0
* *Note 2*: expression `$b|% G*l $_ $y` is shortcut for `$b.GetPixel($_,$y)`. This trick is usefull with gofing, but it slows down the code.

Output with `$b|% G*l $_ $y`:

```
True: 00:01:45.4904622: 22 194 147
True: 00:01:56.4208157: 139 22 194
True: 00:01:46.7629439: 149 144 144
True: 00:01:48.1999005: 132 240 12
True: 00:01:55.8579935:

```

Output with `$b.GetPixel($_,$y)`:

```
True: 00:00:05.7637937: 22 194 147
True: 00:00:06.8743244: 139 22 194
True: 00:00:08.7456055: 149 144 144
True: 00:00:08.5942450: 132 240 12
True: 00:00:06.6495706:

```

Explanation:

* the script creates an array of each pixel color.
* the script applies `gu` (alias for Get-Unique) to the array of color.
* if the result of `hu` is a single element (property `rank` has value for an array only) then output decimal value of R,G,B of this element

# Answer
> 0 votes
**Python 2 + OpenCV + NumPy: 66 characters**

colors.py

```
import numpy as N
def c(i):p=i[0,0];print(p[::-1],"")[N.any(i-p)]

```

test.py

```
import cv2
from colors import c

c(cv2.imread('16C293.png'))
c(cv2.imread('84F00C.png'))
c(cv2.imread('8B16C2.png'))
c(cv2.imread('959090.png'))
c(cv2.imread('falsy.png'))

```

Result:

```
18:14 ~/colors $ python test.py
[ 22 194 147]
[132 240  12]
[139  22 194]
[149 144 144]

18:15 ~/colors $

```

OpenCV is able to read an image and return it as an N-dimensional array. NumPy is used to test the first pixel against the others and either print out the RGB values or blank.

# Answer
> 0 votes
# PHP, 88 bytes

```
function($i){return~-imagecolorstotal($i)?0:sprintf("#%06x",imagecolorsforindex($i,0));}

```

anonymous function takes an indexed PHP image resource as parameter, assumes color in first palette slot, returns color code or 0.

**program, 96 bytes**

```
imagecolorstotal($i=imagecreatefromgif($argv[1]))-1||sprintf("#%06x",imagecolorsforindex($i,0));

```

takes GIF file name from argument, prints color code or nothing. Run with `php -r '<code>' <filename.gif>`.

## for true color images, ~~113~~ 112 bytes

```
function($i){for(;$p<25e4;$p++)$r[$c=imagecolorat($i,$p%500,$p/500)]=1;return~-count($r)?0:sprintf("#%06x",$c);}

```

as above, but requires true color image.

**program, ~~122~~ 116 bytes**

```
for(;$p<25e4;$p++)$r[$c=imagecolorat(imagecreatefrompng($argv[1]),$p%500,$p/500)]=1;count($r)-1||printf("#%06x",$c);

```

as above, but requires PNG file.

---
Tags: code-golf, image-processing
---


# Question
Title: Array indexes to number and number reversed
Given an input array having minimum length `2` and maximum length `9` having any initial values output an array having length `2` consisting of the 1-based indexes of the array represented as either an integer or string in forward and reverse order.

The values of the array or string do not matter and are ignored. For example:

```
[undefined,null] -> [12,21]

```

**Test cases**

Input -\> Output

```
["a","e","i","o","u"] -> [12345,54321] // valid
[{"a":1},{"b":2},{"c":3}] -> [123,321] // valid
[-1,22,33,44,55,66,77,88,99] -> ["123456789","987654321"] // valid
[0,1] -> [01,10] // invalid, not a 1-based index, `01` is not a valid integer
[1999,2000] -> [12,"21"] invalid, output either integers or strings

```

**Winning criteria**

Least bytes.

# Answer
> 7 votes
# Python 2, 53 bytes

```
n=len(input())+1
b=10**n/81-n/9
print[b,10**n/90*n-b]

```

Try it online!

For example, for \\$n=5\\$: \begin{align} 12345 &= 11111 + 1111 + 111 + 11 + 1 \\ &= (11111.\bar1 + 1111.\bar1 + \dots + 1.\bar1) - (0.\bar1 \times 5) \\ &= \frac{10}{9} \left( \sum\_{k=0}^{n-1} 10^{k} \right) - \frac n9 \\ &= \frac{10}{9} \left( \frac{1-10^n}{1-10} \right) - \frac{n}{9} \\ &= \frac{10^{n+1}-1}{81}-\frac{n+1}{9} \end{align}

We use integer (floor) division, so the surplus \\$\frac{1}{81}\\$ gets rounded away.

For the descending part, if `b=12345` we compute something like `66666-12345 == 54321`.

# Answer
> 6 votes
# Python 2, 44 bytes

```
s='123456789'[:len(input())]
print s,s[::-1]

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~55~~ 52 bytes

```
a=''
for i in input():a+=`-~len(a)`
print[a,a[::-1]]

```

Try it online!

Explanation:

```
# initial value: empty string
a=''
# iterate over input
# will work with any iterable object: list, tuple, dict, set, string, etc.
for i in input():
# add to a string representation of its length+1
    a+=`-~len(a)`
# print list, composed from a and its reversed version
print[a,a[::-1]]

```

# Python 2, 66 bytes

```
lambda i:`map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

```

Try it online!

Explanation:

```
lambda i:`map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

# unnamed lambda
# example input: ['q', 'w', 'e', 'r', 't']

# create range from minus length of input to length+1
# ['q', 'w', 'e', 'r', 't'] -> [-5,-4,-3,-2,-1,0,1,2,3,4,5]
                  range(-len(i),-~len(i))
# change every value in range to its absolute value
# [-5,-4,-3,-2,-1,0,1,2,3,4,5] -> [5,4,3,2,1,0,1,2,3,4,5]
          map(abs,range(-len(i),-~len(i)))
# get string representaion of list
# [5,4,3,2,1,0,1,2,3,4,5] -> '[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]'
         `map(abs,range(-len(i),-~len(i)))`
# get each third element from string, starting from index 1, returns string
# '[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]' -> '54321012345'
         `map(abs,range(-len(i),-~len(i)))`[1::3]
# split string over '0', returns list of 2 values
# '54321012345' -> ['54321','12345']
         `map(abs,range(-len(i),-~len(i)))`[1::3].split('0')
# reverse list
# ['54321','12345'] -> ['12345','54321']
         `map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

```

# Answer
> 2 votes
# Jelly, 6 bytes

```
J,JṚ$Ḍ

```

## Explanation

```
J      # Converts an array to [1, ...len(arr)]
 ,     # Paired with
  JṚ$  # The same array as before, reversed.
     Ḍ # Convert the digits to integers.

```

I'm no Jelly master, so likely sub-optimal.

Try it online!

# Answer
> 2 votes
# 05AB1E, 4 bytes

```
āÂ‚J

```

Try it online or verify all test cases.

**Explanation:**

```
ā       # List in the range [1, length of (implicit) input-list]
        #  i.e. ["a","e","i","o","u"] → [1,2,3,4,5]
 Â      # Bifurcated (short for Duplicate & Reverse copy)
  ‚     # Pair both list into a single list of lists
        #  i.e. [1,2,3,4,5] and [5,4,3,2,1] → [[1,2,3,4,5],[5,4,3,2,1]]
   J    # Join the individual items of the inner lists together (and output implicitly)
        #  i.e. [[1,2,3,4,5],[5,4,3,2,1]] → ["12345","54321"]

```

# Answer
> 1 votes
# Python 2, ~~64~~ 60 bytes

```
a=''.join(map(str,range(1,-~len(input()))))
print[a,a[::-1]]

```

Try it online!

-1 with thanks to @KevinCruijssen

-3 with thanks to @DeadPossum

# Answer
> 1 votes
# Husk, 6 bytes

```
S¤,d↔ŀ

```

Try it online!

## Explanation

```
S¤,d↔ŀ  -- input xs (list)
     ŀ  -- indices [1..length xs]
S   ↔   -- do the following with itself and itself reversed:
 ¤,d    -- | undigits and join as tuple

```

# Answer
> 1 votes
# Java (JDK), 76 bytes

```
a->{String[]r={"",""};int i=1;for(var x:a){r[1]=i+r[1];r[0]+=i++;}return r;}

```

Try it online!

# Answer
> 1 votes
# MathGolf, 6 bytes

```
£╒y_xα

```

Try it online!

```
£╒y_xα
£       Length of input array
 ╒      Range from 1 to n
  y     Join
   _x   Duplicate and reverse
     α  Wrap top two elements in array

```

# Answer
> 1 votes
# JavaScript (ES6), 43 bytes

Returns an array of 2 strings.

```
a=>a.map(_=>(a+=++i,b=i+b),i=a=b='')&&[a,b]

```

Try it online!

# Answer
> 1 votes
# Haskell, 42 bytes

*-4 bytes thanks to ovs.*

```
((,)=<<reverse).(`take`"123456789").length

```

Try it online!

# Answer
> 1 votes
# Python 2, 52 bytes

```
x=0
for _ in input():x=x*10+x%10+1
print x,`x`[::-1]

```

Try it online!

# Answer
> 1 votes
# Japt, ~~9~~ 8 bytes

```
Êõ ¬pÔò¶

```

Try it

---

## Explanation

```
Ê            :Length
 õ           :Range [1,Ê]
   ¬         :Join
    p        :Concatenate
     Ô       : Reverse
      ò      :Partition
       ¶     : Between equal characters

```

# Answer
> 1 votes
# Jelly, 4 bytes

```
JṚƬḌ

```

**Try it online!**

### How?

```
JṚƬḌ - Link: list L    e.g. ['ant','bee','cat','dog','elk','frog']
J    - range of length      [1,2,3,4,5,6]
  Ƭ  - 'till (collect up until results are no longer unique):
 Ṛ   -   reverse                         1:[6,5,4,3,2,1] , 2:[1,2,3,4,5,6]=1st
     -                  ->  [[1,2,3,4,5,6],[6,5,4,3,2,1]]
   Ḍ - from base ten        [123456,654321]

```

# Answer
> 0 votes
# Charcoal, 10 bytes

```
⟦⭆θ⊕κ⮌⭆θ⊕κ

```

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

```
  θ    θ    Input array
 ⭆    ⭆     Map over elements and join
    κ    κ  Current index (0-indexed)
   ⊕    ⊕   Increment
     ⮌      Reverse
⟦           Collect into an array

```

# Answer
> 0 votes
# PowerShell, 39 bytes

```
-join(1..($x=$args.count));-join($x..1)

```

Try it online!

Takes input via splatting, which on the command-line prompt looks like, e.g., `$a=(4,3,2); .\array-to-indices.ps1 @a`, and on TIO manifests as separate arguments for each entry.

We take the `.count` of the input `$args`, store that into `$x`. Then construct a range `..` from `1` up to `$x` and `-join` it into a string. Finally we `-join` the range the other direction. Those two strings are left on the pipeline and output is implicit.

# Answer
> 0 votes
# Clean, 53 bytes

```
import StdEnv
$l#n=take(size l)['1'..]
=[n,reverse n]

```

Try it online!

# Answer
> 0 votes
# Scala (60 bytes)

```
def%(s:Seq[Any])={val a=(1 to s.size)mkString;(a,a.reverse)}

```

Try it online

# Answer
> 0 votes
# , 15 bytes

```
4(,:|.)@u:48+#\

```

Try it online!

### How it works

```
4(,:|.)@u:48+#\
             #\  Generate 1-based indices of given array
          48+    Convert digits to ASCII value
4      @u:       Convert to string
 (,:|.)          Append its reverse

```

# Answer
> 0 votes
## JavaScript, 58 bytes

```
_=>[_.map((_,i)=>t.unshift(++i),t=[]),t].map(_=>+_.join``)

```

Try it online!

Pass current index of array plus `1` to `.unshift()` to fill first array with a second array's `.length`, `.join()` each resulting array without any characters separating elements and convert to integer. Returns an array of two integers.

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


title: Html Indentation

text:
# Question
Title: Html Indentation
Given an inconsistently indented piece of html code your task is to return the same text but correctly indented

* Indent space = 4
* Assume input will be non-empty.
* Input can be taken as string or array/list of lines
* Opening and closing tags must be on the same line as long as there is not any other tag inside. `<td></td>`
* Assume there will be only html tags, no text elements whatsoever
* All opening tags that aren't self-closing will have closing tags, and will be given in the correct nesting order. Self-closing tags will be closed with `/>`
* Standard rules apply

**Example and test-cases**

```
Input
--------------
<table>
     <tr>
  <td>
</td>
      <td></td></tr></table>

Output
----------
<table>
    <tr>
        <td></td>
        <td></td>
    </tr>
</table>

```

---

```
Input
------------
<div>
              <ul>
<li></li><li></li></ul>
        <ul>
              <li></li>
<li></li>
</ul><div><table>

<tbody>
  <thead>
 <tr>
        <th></th>
          <th></th>
             </tr>
       </thead>
   <tbody>
<tr>
    <td></td>
    <td></td>
</tr>
<tr>
    <td></td>
    <td></td>
</tr>
</tbody></tbody></table>
       </div>
</div>

Output
--------------------
<div>
    <ul>
        <li></li>
        <li></li>
    </ul>
    <ul>
        <li></li>
        <li></li>
    </ul>
    <div>
        <table>
            <tbody>
                <thead>
                    <tr>
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                    </tr>
                </tbody>
            </tbody>
        </table>
    </div>
</div>

```

---

```
Input
--------------
<div><img src=""/><p></p><input/><input/></div>

Output
-------------
<div>
    <img src=""/>
    <p></p>
    <input/>
    <input/>
</div>

```

# Answer
# Retina, 101 bytes

```
L`<.*?>
T`¶`_`<(.+)¶</\1
^.+
$&/
{`(( *)((?!.*(</|/>)))?.+)/¶(.+)
$1¶$2$#3*4* $5/
    (</.+>/)
$1
/$

```

Try it online! Explanation:

```
L`<.*?>

```

List just the tags.

```
T`¶`_`<(.+)¶</\1

```

Join matching pairs of tags.

```
^.+
$&/

```

Add a marker to the end of the first line.

```
{`(( *)((?!.*(</|/>)))?.+)/¶(.+)
$1¶$2$#3*4* $5/

```

Copy the indentation from each line to the next, adding 4 spaces if the current line is an opening tag.

```
    (</.+>/)
$1

```

But if the next line (which is now the current line) is a closing tag then delete 4 spaces.

```
/$

```

Delete the marker once it reaches the last line.
> 1 votes

# Answer
# Python 2, 170 bytes

```
def f(o,i=-4):
 s,c,n,h,l=" <\n  "
 for t in"".join(o.split()).split(c):
	if'/'==t[:1]:i-=4;h+=(n+i*s)*(l!=t[1:])+c+t
	else:h+=n+i*s+c+t;i+=4-4*('/'in t);l=t
 print h[4:]

```

Try it online!
> 0 votes

# Answer
# Python 2, 174 bytes

```
import re
def F(I):
 m=x=0
 n,s,b='\n/<'
 for d in re.findall(r'<(.*?>)',I):
	if d[0]==s:print(n+' '*~-m*4)*x+b+d,;m-=1;x=1
	else:print n+' '*m*4+b+d,;x*=s in d;m+=not s in d

```

Try it online!
> 0 votes

# Answer
# JavaScript 115 Bytes

```
s=>(n=c=-1,m=f=>"\n"+" ".repeat(4*c)+f,s.replace(/<\/?|\/>/g,w=>w[1]?(n?k=m(w):k=w,n=1,c--,k):m(w,n=0*c++)).trim())

```

I lost the original code so whoops no explanation on this one. It's short though so think of it as a reversing challenge :)

Adds some newlines, but it is correctly tabbed.
> 0 votes

# Answer
# PHP, 141bytes

```
preg_match_all("%(<.*>)%U",$argn,$m);foreach($m[1]as$t)echo!$p|($p=$t[1]!="/")?str_pad("\n",($t[-2]!="/"?$p?++$i:$i--:$i+!$p=0)*4-3):!$i--,$t;

```

Run as pipe with `-nR` or try it online.
> 0 votes

---
Tags: code-golf
---


title: Magrathea 2.0 - Building Mountains

text:
# Question
Title: Magrathea 2.0 - Building Mountains
With the big crash of the universal economy also the demand for custom made planets plunged. The Magratheans had to look after more steady revenues also from a broader class of customers. Therefore, they invented the have-your-own chain of mountain (or short havoc-o-mountains) for people with smaller budget who could not afford a complete planet.

The mountains are build according to the customer's plan (a.k.a. strings of digits and dots) and delivered using ascii-art (consisting of , `/`, `\`, `^` and `v`).

### Task

Write a complete program which takes input (single string) either from STDIN or as argument and outputs to STDOUT. This puzzle is a code-golf so please show some attempt at golfing.

### Input

A string of dots and digits providing the basis for the mountain chain. Each string is exactly as long as necessary to support the mountains and each peak is given by a digit instead of a dot, indicating the height of the peak.

### Output

An ascii version of the mountain chain.

* Each digit in the input represents exactly one peak (`^`) at exactly the height indicated by the digit (i.e. 9 is the highest height).
* There must not be additional peaks in the output (i.e. at places where there is a dot in the input).
* Mountains are of triangular shape, i.e. slopes are created using `/` and `\` characters.
* Passes where two mountains overlap are shaped using the character `v`.
* No superfluous newlines nor blank lines.
* Padding lines with trailing spaces is optional.

You may assume that the input provided is valid, i.e. there always exists a solution according to the rules (e.g. an input of `13..` would not result in a valid configuration and may be ignored). Moreover, on each side there are exactly as many dots such that the mountains must no be cropped.

### Examples

The first line shows the input, all other lines constitute the desired output. (Actually the mountains look much better in my console than here.)

```
1
^

11
^^

1.2.
  ^
^/ \

.2.3..
   ^
 ^/ \
/    \

.2..3..
    ^
 ^ / \
/ v   \

...4...3...3..
   ^
  / \  ^   ^
 /   \/ \ / \
/        v   \

```

# Answer
> 11 votes
## Javascript: ~~272~~ ~~268~~ ~~233~~ ~~232~~ ~~201~~ ~~192~~ ~~189~~ ~~188~~ ~~178~~ 180 characters

Thanks to @Sam for reducing it from 268 to 233 characters, and for @manatwork for another 1 char. @VadimR for pointing out a bug.

```
p=prompt(r=t='');s=' ';for(d=10;d--;r=s+q+s,t+=q.trim()?q+'\n':'')for(q='',i=0;i<p.length;)q+=' \\/v^'[p[i++]==d?4:(/\^|\\/.test(r[i-1])+2*/\^|\//.test(r[i+1]))*(r[i]==s)];alert(t)

```

Properly idented and somewhat ungolfed version with comments:

```
// The output initialization is just a golfing trick suggested by @manatwork.
input = prompt(state = output = '');
space = ' ';

// Repeat for each line, from the top (the highest peak, highest digit) to the floor (digit 1). Start at 10 to avoid a bug.
for (digit = 10; digit--;

      // Update the state of our automaton, at the end of the iteration.
      // Add a space after and before to simplify the future pattern recognization.
      state = space + line + space,

      // Add the line to the output if it is not an empty line, at the end of the iteration.
      output += line.trim() ? q + '\n' : '')
{ // This curly brace was added for readability, it is not in the golfed source.

  // Analyze each character in the current state to produce a new state, like a cellular automaton.
  for (line = '', i = 0; i < input.length;)
  { // This curly brace was added for readability, it is not in the golfed source.
    line +=

        // If the input is the current digit number, evaluate to 4 and put a peak in this character.
        // Otherwise evaluate this expression with those rules:
        // 1 means that the hill is higher only at right in the previous iteration, we do climb it to the right in this one.
        // 2 means that the hill is higher only at left in the previous iteration, we do climb it to the left in this one.
        // 3 means that the hill is higher at both sides in the previous iteration, we are in a v-shaped valley.
        // 0 means nothing to do here. If the middle is not a space, it will be multiplied by 0 and become 0.
        ' \\/v^'[input[i++] == digit ? 4 : (/\^|\\/.test(state[i - 1]) + 2 * /\^|\//.test(state[i + 1])) * (r[i] == space)];
    } // This curly brace was added for readability, it is not in the golfed source.
} // This curly brace was added for readability, it is not in the golfed source.

// Give the final output.
alert(output);

```

As you may note from the code, this works as a cellular automaton, where each cells checks for a number in the input, looks to itself and to its two neighbours to decide what the next iteration will be. At each moment a cell may be a `^`, `/`, `\`, `v` or . The input provided in the test cases produces the expected output.

Note that using the `alert` box sucks, since it normally does not have a monospaced font. You may copy & paste the text from the `alert` box to somewhere else for a better appreciation of the output, or you may replace the last line `alert` by `console.log`, but since this is code-golf, `alert` is shorter.

Further, it does not validates anything in the input. It simply considers unrecognized characters as spaces the same way it does to `.` (in fact `.` is an unrecognized character too).

# Answer
> 6 votes
## Ruby, ~~208~~ ~~201~~ 189

Very fun challenge! Here's an alternative Ruby solution.

```
gets.size.times{|x|0.upto(h=$_[x].to_i-1){|d|r=$*[h-d]||=' '*~/$/
[x+d,x-d].map{|o|r[o]=r[o]>?!??v:o<x ??/:?\\if r[o]<?w}
d<1?r[x]=?^:r[x-d+1,w=2*d-1]=?w*w}}
puts$*.reverse.*($/).tr(?w,' ')

```

As a bonus, here's a Ruby implementation of Victor's very clever "cellular automaton" algorithm, at 162 characters:

```
s=gets
9.downto(1){|h|$0=(-1..s.size).map{|x|$_=$0[x,3]
s[x]=="#{h}"??^:~/  [\^\/]/??/:~/[\^\\]  /??\\:~/[\^\\] [\^\/]/??v:' '}*''
$*<<$0[1..-2]if$0=~/\S/}
puts$*

```

Example output:

```
....5.....6..6.....
          ^  ^
    ^    / \/ \
   / \  /      \
  /   \/        \
 /               \
/                 \

```

# Answer
> 4 votes
C# - 588 characters - not as good as Ray's 321 though!

```
class P{static void Main(string[] a){char[,] w=new char[a[0].Length+1,10];int x=0;foreach(char c in a[0]){if(c!='.'){int h=int.Parse(c+"");if(w[x,h]=='\0')w[x,h]='^';int s=1;for(int l=h-1;l>0;l--){for(int m=x-s;m<=x+s;m++){if(w[m,l]!='\0'){if(w[m,l]=='^')w[m,l]='/';if(w[m,l]=='\\')w[m,l]='v';}else{if(m==x-s)w[m,l]='/';else if(m==x+s)w[m,l]='\\';else w[m,l]='\0';}bool t=false;for(int f=9;f>0;f--){if(t)w[m,f]='\0';if(w[m,f]!='\0')t=true;}}s++;}}x++;}for(int k=9;k>0;k--){string u="";for(int j=0;j<w.GetLength(0);j++){u+=w[j,k];}if(u.Replace("\0","")!="")System.Console.WriteLine(u);}}}

```

Example output:

```
F:\>mountains ".2..3..4..."
       ^
    ^ / \
 ^ / v   \
/ v       \

```

Or a longer more complex one...

```
F:\>mountains ".2..3..6.....5...3......1..3..4....2."
       ^
      / \    ^
     /   \  / \               ^
    /     \/   \ ^         ^ / \
 ^ /            v \       / v   \  ^
/ v                \    ^/       \/ \

```

Brilliant puzzle... not as easy as it seems... loved it!

# Answer
> 4 votes
# APL, 65 bytes

`⍉⌽↑⌽¨h↑¨'^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h←¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a←11|⎕d⍳⍞]`

this symbol returns raw (not evaluated) input as a character array.

Solving interactively, in an APL session:

```
      s←'...4...3...3..' ⍝ let's use s instead of ⍞
      ⎕d ⍝ the digits
0123456789
      ⎕d⍳s ⍝ the indices of s in ⎕d or 11-s if not found
11 11 11 5 11 11 11 4 11 11 11 4 11 11
      11|⎕d⍳s ⍝ modulo 11, so '.' is 0 instead of 11
0 0 0 5 0 0 0 4 0 0 0 4 0 0
      a←11|⎕d⍳s ⍝ remember it, we'll need it later
      ⍴a ⍝ length of a
14
      ⍳⍴a
1 2 3 4 5 6 7 8 9 10 11 12 13 14
      ⍝ ∘.-    subtraction table
      ⍝ ∘.-⍨A  same as: A ∘.- A
      ⍝ |      absolute value
      |∘.-⍨⍳⍴a
 0  1  2  3 4 5 6 7 8 9 10 11 12 13
 1  0  1  2 3 4 5 6 7 8  9 10 11 12
 2  1  0  1 2 3 4 5 6 7  8  9 10 11
 ...
13 12 11 10 9 8 7 6 5 4  3  2  1  0
      ⍝ ↓      split the above matrix into rows
      ⍝ a-     elements of "a" minus corresponding rows
      ⍝ ⊃⌈/    max them together
      ⊃⌈/a-↓|∘.-⍨⍳⍴a
2 3 4 5 4 3 3 4 3 2 3 4 3 2
      ⍝ This describes the desired landscape,
      ⍝ except that it's a little too high.
      ⍝ Add -1 to correct it:
      ¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a
1 2 3 4 3 2 2 3 2 1 2 3 2 1
      ⍝ Perfect!  Call it "h":
      h←¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a
      0,⍨h ⍝ append a 0 (same as h,0)
1 2 3 4 3 2 2 3 2 1 2 3 2 1 0
      0,0,⍨h ⍝ also prepend a 0
0 1 2 3 4 3 2 2 3 2 1 2 3 2 1 0
      2-/0,0,⍨h ⍝ differences of pairs of consecutive elements
¯1 ¯1 ¯1 ¯1 1 1 0 ¯1 1 1 ¯1 ¯1 1 1 1
      ⍝ this gives us slopes between elements
      2+/2-/0,0,⍨h ⍝ sum pairs: left slope + right slope
¯2 ¯2 ¯2 0 2 1 ¯1 0 2 0 ¯2 0 2 2
      ×2+/2-/0,0,⍨h ⍝ signum of that
¯1 ¯1 ¯1 0 1 1 ¯1 0 1 0 ¯1 0 1 1
      2+×2+/2-/0,0,⍨h ⍝ add 2 to make them suitable for indexing
1 1 1 2 3 3 1 2 3 2 1 2 3 3
      ⍝ Almost ready.  If at this point we replace
      ⍝ 1:/ 2:v 3:\, only the peaks will require fixing.
      ~×a ⍝ not signum of a
1 1 1 0 1 1 1 0 1 1 1 0 1 1
      (~×a)×2+×2+/2-/0,0,⍨h ⍝ replace peaks with 0-s
1 1 1 0 3 3 1 0 3 2 1 0 3 3
      ⍝ Now replace 0:^ 1:/ 2:v 3:\
      ⍝ We can do this by indexing a string with the vector above
      ⍝ (and adding 1 because of stupid 1-based indexing)
      '^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h]
///^\\/^\v/^\\
      ⍝ Looks like our mountain, only needs to be raised according to h
      r←'^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h] ⍝ name it for convenience
      h¨↑r ⍝ extend r[i] with spaces to make it h[i] long
 /  /   /    ^     \    \   /   ^    \   v  /   ^    \   \
      ↑⌽¨h¨↑r ⍝ reverse each and mix into a single matrix
/
 /
  /
   ^
  \
 \
 /
  ^
 \
v
 /
  ^
 \
\
      ⍉⌽↑⌽¨h¨↑r ⍝ reverse and transpose to the correct orientation
   ^
  / \  ^   ^
 /   \/ \ / \
/        v   \

```

# Answer
> 3 votes
# Ruby, 390 characters

Whew, this one was tricky.

I ended up having to append to a new string for each character, using a variable `s` that meant "skip next character" which was needed for processing `^` and `\`.

This output exactly the given sample output for all of the test cases.

```
m=[gets.chomp]
a=m[0].scan(/\d/).max.to_i
m[0].gsub!(/./){|n|n==?. ? ' ':a-n.to_i}
s=nil
until a==0
o=''
m[-1].chars{|c|o+=case c
when ?0;?^
when ' ';t=s;s=nil;t ? '':' '
when /\d/;(c.to_i-1).to_s
when ?^;s=1;o.slice! -1;"/ \\"
when ?/;t=s;s=nil;t ? "#{o.slice! -1;' '}":o.slice!(-1)=='\\' ? 'v ':"/ "
when ?\\;s=1;' \\'
when ?v;' '
end}
m.push o
a-=1
end
puts (m[1..-1]*"\n").gsub /\d/,' '

```

Chart of what the variables mean:

```
m | The mountain array.
a | The highest height of a mountain. Used for counting when to stop.
s | Whether or not to skip the next character. 1 for yes, nil for no.
o | Temp string that will be appended to mountain.
t | Temp variable to hold the old value of s.

```

I'm sure I could golf it down *much* more, but I have to go now. Shall be improved later!

# Answer
> 2 votes
# Java, 377 407

**Edit:** @Victor pointed out that this needed to be a complete program, so I added a few dozen characters to make it compilable and runnable. Just pass the "purchase order" as the first param when executing the program, like so: `java M ..3.4..6..4.3..`

I think this is similar in spirit to other answers, basically just traverses the "mountain order" repeatedly for every possible height, and builds the mountains from the tops down. That way I only have to deal with four conditions if not building a peak -- either an up slope '/', down slope '\\, joint 'v', or empty ' '. I can discover that simple by looking at the three spaces centered "above" my current position in my top-down build.

Note that like other submissions, I treat anything other than a number as equivalent to '.' in the input, for brevity.

Golfed version:

```
class M{public static void main(String[]m){char[]n=m[0].toCharArray();int e=n.length,h=9,x=-1,p;char[][]o=new char[11][e];char l,r,u;boolean a,b,c;for(;h>=0;h--){for(p=0;p<e;p++){if(n[p]-49==h){o[h][p]=94;if(x==-1)x=h;}else{l=(p>0)?o[h+1][p-1]:0;r=(p<e-1)?o[h+1][p+1]:0;u=o[h+1][p];a=l>91&&l<99;b=r==94||r==47;c=u<33;o[h][p]=(char)((a&&b)?'v':(c&&b)?47:(c&&a)?92:32);}}if(x>=h)System.out.println(o[h]);}}}

```

Human readable form (and without some of the equivalent transmogrifications to achieve golf form):

```
class Magrathea2 {
    public static void main(String[] mountain) {
        String out = "";
        char[][] output = new char[11][mountain[0].length()];
        int height = 9; int maxheight = -1;
        int position = 0;
        char left,right,up;
        char[] mount = mountain[0].toCharArray();
        for (; height >= 0; height--) {
            for (position=0; position < mount.length; position++) {
                if (mount[position]-49 == height) {
                    output[height][position] = '^';
                    if (maxheight==-1) {
                        maxheight=height;
                    }
                } else { // deal with non-numbers as '.'
                    left=(position>0)?output[height+1][position-1]:0;
                    right=(position<mount.length-1)?output[height+1][position+1]:0;
                    up=output[height+1][position];
                    if ((left=='^'||left=='\\')&&(right=='^'||right=='/')) {
                        output[height][position]='v';
                    } else if ((up==' '||up==0)&&(right=='/'||right=='^')) {
                        output[height][position]='/';
                    } else if ((up==' '||up==0)&&(left=='\\'||left=='^')) {
                        output[height][position]='\\';
                    } else {
                        output[height][position]=' ';
                    }
                }
            }
            if (maxheight >= height) {
                out+=new String(output[height]);
                if (height > 0) {
                    out+="\n";
                }
            }
        }
        System.out.println(out);
    }
}

```

Enjoy.

Example output:

```
$ java M ..3..4...6...5....1
         ^
        / \  ^
     ^ /   \/ \
  ^ / v        \
 / v            \
/                \^

```

# Answer
> 2 votes
## Perl 6, 264 224 216 206 200 194 124 bytes

```
$_=get;my$a=10;((s:g/$a/^/;s:g/\s\.\s/ v /;s:g'\.\s'/ ';s:g/\s\./ \\/;$!=say TR/.1..9/ /;tr'^\\/v' ')if .match(--$a)|$!)xx 9

```

Thanks to @JoKing for showing a s/// solution. This is golfed a bit further after fixing the tr/// bug in Perl 6.

My original solution with subst:

```
my$t=get;for 9...1 {if $t.match($_)|$! {$t=$t.subst($_,'^',:g).subst(' . ',' v ',:g).subst('. ','/ ',:g).subst(' .',' \\',:g);$!=say $t.subst(/<[\.\d]>/,' ',:g);$t.=subst(/<[^\\/v]>/,' ',:g)};}

```

Ungolfed:

```
my $t=slurp;
my $s;
for 9...1 {
    if $t.match($_)||$s {                    # match number or latched
        $t=$t.subst($_,'^',:g)               # peaks
        .subst(' . ',' v ',:g)               # troughs
        .subst('. ','/ ',:g)                 # up slope
        .subst(' .',' \\',:g);               # down slope
        $s=say $t.subst(/<[\.\d]>/,' ',:g);  # clean, display, latch
        $t=$t.subst(/<[^\\/v]>/,' ',:g)      # wipe for next line
    }
}

```

Output:

```
...4...3...33..4..4....2.3.22.33.5..22...333.222.3..
                                 ^
   ^           ^  ^             / \
  / \  ^   ^^ / \/ \     ^    ^^   \     ^^^     ^
 /   \/ \ /  v      \  ^/ \^^/      ^^  /   \^^^/ \
/        v           \/               \/           \

```

# Answer
> 1 votes
# C# - ~~321~~ 319

```
using System.Linq;class P{static void Main(string[]p){int h=p[0].Max()-48,i=h,j,n=p[0].Length;char[]A=new char[n+2],B=A;for(;i-->0;){for(j=0;j++<n;){var r=(A[j+1]==47|A[j+1]==94);B[j]=(char)(p[0][j-1]==i+49?94:i+1<h?A[j]==0?(A[j-1]>90&A[j-1]<95)?r?118:92:r?47:0:0:0);}A=(char[])B.Clone();System.Console.WriteLine(B);}}}

```

Ungolfed and commented:

```
using System.Linq;

class P
{
    static void Main(string[] p)
    {
        int h = p[0].Max() - 48,    // Getting the height. Codes for 0 to 9 are 48 to 57, so subtract 48 and hope no one will input anything but dots and numbers.
            i = h,
            j,                      // Declaring some iterators here, saves a few chars in loops.
            n = p[0].Length;
        char[] A = new char[n+2],   // Creating an array of char with 2 extra members so as not to check for "index out of bounds" exceptions
               B = A;               // B is referencing the same array as A at this point. A is previous row, B is the next one.
        for (;i-->0;)               // Looping from top to the bottom of the mountain
        {
            for (j = 0; j++ < n;)   // Looping from left to right.
            {
                var r = (A[j + 1] == 47 | A[j + 1] == 94);  // This bool is used twice, so it saves a few characters to make it a variable

                // Here's the logic
                B[j] = (char)(p[0][j - 1] == i + 49 ? 94    // If at this position in the string we have a number, output "^"
                                           : i + 1 < h ?    // And if not, check if we're on the top of the mountain
                                             A[j] == 0 ?    // If we're not at the top, check if the symbol above is a space (0, actually)
                                            (A[j - 1] > 90 & A[j - 1] < 95) ?   // If there's nothing above, we check to see what's to the left ( ^ or \ )
                                             r ?            // And then what's to the right ( ^ or / )
                                             118            // If there are appropriate symbols in both locations, print "v"
                                           : 92             // If there's only a symbol to the left, print "\"
                                           : r              // Otherwise check if there's a symbol to the right, but not to the left
                                           ? 47             // And if there is, print "/"
                                           : 0 : 0 : 0);    // Print nothing if there aren't any symbols above, to the left and to the right,
                                                            // or there's a "^" right above, or we're at the top of the mountain
            }
            A=(char[])B.Clone();    // Clone arrays to iterate over the next line
            System.Console.WriteLine(B);
        }
    }
}

```

Example:

```
C:\>program .2..3..4...
        ^
     ^ / \
  ^ / v   \
 / v       \

```

I think it outputs an extra space before each line, though.

# Answer
> 1 votes
## Perl, ~~254 218~~ 212

```
$s=<>;sub f{9-$i-$_[0]?$":pop}for$i(0..8){$h=1;$_=$s;s!(\.*)(\d?)!$D=($w=length$1)+$h-($2||1);join'',(map{($x=$_-int$D/2)<0?f--$h,'\\':$x?f++$h,'/':$D%2?f--$h,v:f$h,'/'}0..$w-1),$2?f$h=$2,'^':''!ge;print if/\S/}

```

```
$s=<>;
sub f{9-$i-$_[0]?$":pop}
for$i(0..8){
    $h=1;
    $_=$s;
    s!(\.*)(\d?)!
        $D=($w=length$1)+$h-($2||1);
        join'',(map{
            ($x=$_-int$D/2)<0
                ?f--$h,'\\'
                :$x
                    ?f++$h,'/'
                    :$D%2
                        ?f--$h,v
                        :f$h,'/'
        }0..$w-1),$2
            ?f$h=$2,'^'
            :''
    !ge;
    print if/\S/
}

```

**Edit:** actually it's a bug-fix to work with ProgrammerDan's `..3..4...6...5....1` example, but, in the process, some bytes were off. And online test: https://ideone.com/P4XpMU

# Answer
> 1 votes
# CJam, ~~128~~ ~~117~~ ~~112~~ ~~106~~ 104 bytes

CJam is a bit younger than this challenge so this answer does not compete. This was a very nice challenge though! From the little I know about J and APL, I think a submission in those would be impressively short.

```
WlW++"."Waer{_{~U(e>:U}%\W%}2*;W%]z{$W=}%_$W=S*\:L,2-,\f{\_)L=(~"^/ ^^/ \v ^ \\"S/2/@L>3<_$0=f-{=}/t}zN*

```

Here is a test case, which I think contains all possible possible combinations of slopes, peaks and troughs:

```
...4...3...33..4..4....2.3.22.33.5..22...333.222.3..

```

which yields

```
                                 ^
   ^           ^  ^             / \
  / \  ^   ^^ / \/ \     ^    ^/   \     ^^^     ^
 /   \/ \ /  v      \  ^/ \^^/      \^  /   \^^^/ \
/        v           \/               \/           \

```

Test it here.

I'll add an explanation for the code later.

# Answer
> 1 votes
## Python, ~~297~~ ~~234~~ 218

-63 bytes thanks to Jo King
-16 bytes with `r=s.replace` instead of lambda

```
s=input()
r=s.replace
q=0
j=''.join
for i in range(9):
 if`9-i`in s or q:q=s=r(`9-i`,'^');s=r(' . ',' v ');s=r('. ','/ ');s=r(' .',' \\');print j([x,' '][x in'0123456789.']for x in s);s=j([x,' '][x in'/\^v']for x in s)

```

Takes input from STDIN. Ungolfed, simplified:

```
s=input() # Take input
r=lambda y,z: s.replace(y,z) # Function for quick s.replace(a, b)
j=lambda x: ''.join(x)
q=0 # Acts like boolean
for i in range(9): # Count to 9
 if `9-i`in s or q: # When digit has been found or found previously (no newlines at start)
  q=s=r(`9-i`,'^') # Digit to ^, set q to non-zero value for always executing from now on
  s=r(' . ',' v ') # ' . ' to ' v '
  s=r('. ','/ ') # '. ' to '/ '
  s=r(' .',' k') # ' .' to 'k'. K is a placeholder, since \\ takes two chars and `[...]`[2::5] fails
  print j([x,' '][x in'0123456789.']for x in s) # Print without '0123456789.'
  s=j([x,' '][x in'/\^v']for x in s) # Wipe (delete '/^\v`)

```

# Answer
> 0 votes
# Powershell, ~~148~~ 145 bytes

It's a nice challenge!

```
param($s)9..1|?{($p+=$s-match$_)}|%{"$_,^; \. , v ;\. ,/ ; \., \;\^|\\|/|v, "-split';'|%{$x=$s-replace'\.|\d',' '
$s=$s-replace($_-split',')}
$x}

```

Less golfed test script:

```
$f = {

param($s)
9..1|?{($p+=$s-match$_)}|%{      # loop digits form 9 downto 1, execute to the end as soon as a suitable digit met
    $s=$s-replace$_,'^'          # replace current digit with '^'
    $s=$s-replace' \. ',' v '    # replace ' . '  with ' v '
    $s=$s-replace'\. ','/ '      # replace '. ' with '/ '
    $s=$s-replace' \.',' \'      # replace ' .' with ' \'
       $s-replace'\.|\d',' '     # replace all dots and digits with ' ' and push to output. Don't store this replacement
    $s=$s-replace'\^|\\|/|v',' ' # prepeare to the next step: replace ^ \ / and v to space
}

    # Example:
    #     $s="...4...3...3.."
    # 4 : $s="...^...3...3.." output: "   ^          "
    # 4 : $s="... ...3...3.."
    # 3 : $s="../ \..^...^.." output: "  / \  ^   ^  "
    # 3 : $s="..   .. ... .."
    # 2 : $s="./   \/ \./ \." output: " /   \/ \ / \ "
    # 2 : $s=".        .   ."
    # 1 : $s="/        v   \" output: "/        v   \"
    # 1 : $s="              "

}

@(
    ,("1",
      "^")

    ,("11",
      "^^")

    ,("1.2.",
    "  ^ ",
    "^/ \")

    ,(".2.3..",
      "   ^  ",
      " ^/ \ ",
      "/    \")

    ,(".2..3..",
      "    ^  ",
      " ^ / \ ",
      "/ v   \")

    ,("...4...3...3..",
      "   ^          ",
      "  / \  ^   ^  ",
      " /   \/ \ / \ ",
      "/        v   \")

    ,("...4...3...33..4..4....2.3.22.3..5...22...333.222.3..",
      "                                 ^                   ",
      "   ^           ^  ^             / \                  ",
      "  / \  ^   ^^ / \/ \     ^    ^/   \      ^^^     ^  ",
      " /   \/ \ /  v      \  ^/ \^^/      \^^  /   \^^^/ \ ",
      "/        v           \/                \/           \")

    ,(".2..3..6.....5...3......1..3..4....2.",
      "       ^                             ",
      "      / \    ^                       ",
      "     /   \  / \               ^      ",
      "    ^     \/   \ ^         ^ / \     ",
      " ^ /            v \       / v   \  ^ ",
      "/ v                \    ^/       \/ \")
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$result"-eq"$expected"
    $s
    $result
}

```

Output:

```
True
1
^
True
11
^^
True
1.2.
  ^
^/ \
True
.2.3..
   ^
 ^/ \
/    \
True
.2..3..
    ^
 ^ / \
/ v   \
True
...4...3...3..
   ^
  / \  ^   ^
 /   \/ \ / \
/        v   \
True
...4...3...33..4..4....2.3.22.3..5...22...333.222.3..
                                 ^
   ^           ^  ^             / \
  / \  ^   ^^ / \/ \     ^    ^/   \      ^^^     ^
 /   \/ \ /  v      \  ^/ \^^/      \^^  /   \^^^/ \
/        v           \/                \/           \
True
.2..3..6.....5...3......1..3..4....2.
       ^
      / \    ^
     /   \  / \               ^
    ^     \/   \ ^         ^ / \
 ^ /            v \       / v   \  ^
/ v                \    ^/       \/ \

```

# Answer
> 0 votes
# Pip `-l`, 100 bytes

```
Y#aZGMXaFi,#aIh:+a@i{(yi--h):4j:0Wh-j&++(yi-++jh-j)(yi+jh-j):2}RV Z(J*y)R`.(?=.*[^0])`0R,6;^" /\v^^"

```

*(The language is newer than the question, but probably isn't going to beat the APL submission anyway. Although I hope it will get much shorter.)*

Takes input via command-line argument. Try it online!

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


title: Hack g-code.js parser

text:
# Question
Title: Hack g-code.js parser
Here you can see g-code parser, written in JavaScript to use in microcontroller (like espruino). But you can run it in browser, because it don't use any specific features.

```
function gcode(str){
  //Removes comment, parses command name and args
  const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]);
  //A1.2 B43 C -> {A: 1.2, B: 42, C: 0}
  eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})");
}
const G1 = console.log;
gcode(prompt("crackme"));
```

When you pass `G1 X3 Y4.53 Z42` to `gcode()`, it runs `G1({X: 3, Y: 4.53, Z: 42})`. As you can see, it uses `eval`, protected by regexp. But despite of this, you can attack this function and cause remote code execution. Your goal is to run `alert("pwned")`. This is code golf, so shortest working input wins

# Answer
> 7 votes
# 112 bytes

```
G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()

```

```
function gcode(str){
  //Removes comment, parses command name and args
  const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]);
  //A1.2 B43 C -> {A: 1.2, B: 42, C: 0}
  eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})");
}
const G1 = console.log;

payload = `G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()`;
gcode(payload);
```
* Each `ƒ` (U+0192), `Τ` (U+03A4) cost 2 bytes, they are not as same as ASCII `f`, `T`.

---

The `gcode` function will keep any `/\W/` characters as is. So, we just need to use these characters to write some logic here. The idea is basically based on how JSF\**k works. We construct the codes like this:

```
(()=>{})["constructor"]('alert("pwned")')

```

We need string literal `"constructor"` and `alert("pwned")`. But `gcode` convert `"constructor"` to `"c: +0,o: +0,n: +0,....r: +0"`. So we need to convert the string back. We use this function to do the convert:

```
ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):''

```

`Τ` is the text inputed, $ is index. We first initialize `$` to 0 using `+[]`. Then we output the character at the index position, and check if next character is `":"`, if so we skip the following 5 characters.

---

Thanks to l4m2, saves few bytes.

---
Tags: code-golf, javascript
---


title: Calculate the inverse modulus

text:
# Question
Title: Calculate the inverse modulus
# The task:

Output a value for `x`, where `a mod x = b` for two given values `a,b`.

# Assumption

* `a` and `b` will always be positive integers
* There won't always be a solution for `x`
* If multiple solutions exist, output at least one of them.
* If there aren't any solutions, output nothing or some indication that no solutions exist.
* Built-ins are allowed (not as fun as other mathematical approaches)
* Outputs are always integers

# Examples

```
A, B >> POSSIBLE OUTPUTS

5, 2 >> 3
9, 4 >> 5
8, 2 >> 3, 6
6, 6 >> 7, (ANY NUMBER > 6)
8, 7 >> NO SOLUTION
2, 4 >> NO SOLUTION
8, 5 >> NO SOLUTION
10,1 >> 3, 9

```

This is , so lowest bytes wins.

# Answer
# JavaScript, ~~28~~ ~~27~~ ~~26~~ ~~24~~ 23 bytes

```
a=>b=>(a-=b)?a>b&&a:b+1

```

Try it online!

`false` indicates no solution.

-1 thanks @Arnauld
> 11 votes

# Answer
# MATL, 6 bytes

```
tQ:\=f

```

Try it online! Or verify all test cases.

### Explanation

Consider inputs `8`, `2` as an example.

```
t    % Implicit input. Duplicate                STACK: 8, 8
Q    % Add 1                                    STACK: 8, 9
:    % Range                                    STACK: 8, [1 2 3 4 5 6 7 8 9]
\    % Modulo                                   STACK: [0 0 2 0 3 2 1 0 8]
=    % Implicit input. Equality comparison      STACK: [0 0 1 0 0 1 0 0 0]
f    % Indices of nonzeros. Implicit display    STACK: [3 6]

```
> 6 votes

# Answer
# Python 2, ~~40~~ 34 bytes

-6 bytes thanks to Bubbler

```
lambda a,b:[(a==b)*-~a,a-b][a>b*2]

```

Try it online!
> 5 votes

# Answer
# Jelly, 5 bytes

```
‘R⁸%i

```

Returns the minimal valid **x** or **0** is there is none.

Try it online!
> 4 votes

# Answer
# Groovy, 48 bytes (using built-in):

```
{a,b->Eval.me(a+"g").modInverse(Eval.me(b+"g"))}

```

---

`Eval.me(...+"g")` \- Affixes "g" to the input, making it a BigInteger.

`modInverse(...)` \- Performs the inverse modulo operation.

---

# Java 8, 70 bytes

```
{a,b->return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(b));}

```
> 3 votes

# Answer
# , ~~33~~ 28 bytes

```
pryr::f(match(b,a%%1:(a+1)))

```

Try it online!

-4 bytes thanks to Jarko Dubbeldam.

-1 byte thanks to Giuseppe.

Returns `NA` if there is no solution. TIO doesn't have the pryr library installed, so the code at that link uses `function(a,b)` instead.
> 3 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
³%_⁴
r‘ÇÐḟ

```

A full program taking the two positive integers, `a` and `b`, and printing a list of the integer solutions between `min(a,b)+1` and `max(a,b)+1` inclusive.

**Try it online!**
> 1 votes

# Answer
## Mathematica 36 Bytes

```
a_±b_:=Select[Range[9a],a~Mod~#==b&]

```

Input:

```
5 ± 2
9 ± 4
8 ± 2
6 ± 6
8 ± 7
2 ± 4
8 ± 5
10 ± 1

```

Output:

```
{3}
{5}
{3, 6}
{7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, \
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, \
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54}
{}
{}
{}
{3, 9}

```
> 1 votes

# Answer
# Haskell, 33 bytes

Crashes with `code.hs: out of memory (requested ??? bytes)` if there is no solution (times out on TIO before that):

```
a!b=[x|x<-[b+1..],mod(a-b)x<1]!!0

```

Try it online!

Thanks at Ørjan Johansen for spotting a mistake!
> 1 votes

# Answer
# C# (Mono C# compiler), ~~57 56~~ 26 bytes

Port of Rod's Python answer. Thanks to W W for -1 byte.

HUGE thanks to Kevin Cruijssen for -30 bytes.

```
a=>b=>a-b>b?a-b:a==b?a+1:0
```

Try it online!
> 1 votes

# Answer
# Pyth, 16 bytes

```
hhx!0mqeQ%hQdShh

```

Try it online!

All test cases

Takes input as `[a, b]`, errors if no solution found. Will revise if erroring isn't allowed.
> 0 votes

# Answer
# Axiom, ~~147~~ 128 bytes

```
g(a:PI,c:PI):Union(List PI,Stream INT)==(a<c=>[];r:=a-c;r=0=>expand((a+1..)::UniversalSegment INT);[b for b in divisors(r)|b>c])

```

ungolf it and test

```
--a%b=c return all possible b
f(a:PI,c:PI):Union(List PI, Stream INT)==
    a<c=>[]
    r:=a-c
    r=0=>expand((a+1..)::UniversalSegment INT)
    [b  for b in divisors(r)|b>c]

(3) -> [[i,j,g(i,j)] for i in [5,9,8,6,8,2,8,10] for j in [2,4,2,6,7,4,5,1]]
   (3)
   [[5,2,[3]], [9,4,[5]], [8,2,[3,6]], [6,6,[7,8,9,10,11,12,13,14,15,16,...]],
    [8,7,[]], [2,4,[]], [8,5,[]], [10,1,[3,9]]]
                                                      Type: List List Any

```

This would find all the solution even the infinite set solution...
> 0 votes

# Answer
# APL (Dyalog Unicode), 19 bytes

```
A←{(⍳⍵+1)/⍨⍺=⍵|⍨⍳⍵+1}

```

Try it online!

Golfing in progress...
> 0 votes

# Answer
# Mathematica, 28 bytes

```
Which[#>2#2,#-#2,#==#2,#+1]&

```
> 0 votes

# Answer
# PHP\>=7.1, 51 Bytes

```
for([,$a,$b]=$argv;++$x<2*$a;)$a%$x!=$b?:print$x._;

```

Online Version
> 0 votes

# Answer
# Pip, 9 bytes

```
a%,a+2@?b

```

Takes the two numbers as command-line arguments. Outputs the smallest solution, or nil if no solution exists. Try it online!

### Explanation

```
           a, b are cmdline args (implicit)
  ,a+2     Range from 0 up to but not including a+2
a%         Take a mod each of those numbers
           (Note that a%0 returns nil; it emits a warning, but only if warnings are turned on)
      @?b  Find the index of the first occurrence of b in this list, or nil if it doesn't occur
           Autoprint (implicit)

```

For example, with input of `8` and `2`:

```
   a+2   10
  ,      [0 1 2 3 4 5 6 7 8 9]
a%       [() 0 0 2 0 3 2 1 0 8]

```

The 0-based index of the first occurrence of `2` in this list is `3`, which is our solution.
> 0 votes

# Answer
# , 14 bytes

```
(->]){-,~=*1+]

```

Try it online!

Translation of Rod's Python 2 solution.

### How it works

The rare cases where a J code can be directly translated into Python.

```
(->]){-,~=*1+]  <=>  [(a==b)*(1+b),a-b][a-b>b]
         =*1+]        (a==b)*(1+b)
      -,~            [            ,a-b]
     {                                 [     ]
(->])                                   a-b>b

```
> 0 votes

# Answer
# Japt, 13 bytes

```
UµV ?U>V©U:ÒV

```

Try it online!

Translation of eush77's JS solution.

The code is just `(U-=V)?U>V&&U:-~V` when transpiled to JS, where `U` and `V` are the two input values.
> 0 votes

# Answer
# Ruby, 31 bytes

```
->a,b{(1..a+1).find{|x|a%x==b}}

```

Try it online!
> 0 votes

# Answer
# Japt, 7 bytes

(Eventually) Outputs `undefined` if there's no solution.

```
@%X¥V}a

```

Try it here
> 0 votes

# Answer
# Perl 6, 23 bytes

```
{grep $^a%*==$^b,^$a+2}

```

Try it online!

Anonymous code block that returns a list of possible values from `2` up to `a+1`
> 0 votes

# Answer
# ORK, 566 bytes

```
When this program starts:
I have a inputter called I
I have a number called a
I have a number called b
I is to read a
I is to read b
I have a mathematician called M
M's first operand is a
M's second operand is b
M is to subtract
I have a number called n
n is M's result
M's first operand is b
M's second operand is n
M is to compare
I have a scribe called W
If M says it's less then W is to write n
If M says it's less then W is to write "\n"
M's second operand is a
M is to compare
If M says it's equal then W is to write a
If M says it's equal then W is to write a

```

Try it online!

**O**bjects **R** **K**ool. Luckily, however, I didn't need to use any (besides the built-in ones) for this task.
> 0 votes

# Answer
## F#, 40 bytes

```
let m a b=Seq.find(fun x->a%x=b){1..a+1}

```

Try it online!

Pretty straight-forward. Throws a `System.Collections.Generic.KeyNotFoundException` if no solution can be found.

You could also modify it to `Seq.tryFind`, which will return an `int option`, with `None` if no solution could be found.
> 0 votes

# Answer
# 05AB1E, 7 bytes

```
>Lʒ¹s%Q

```

Try it online or verify all test cases.

**Explanation:**

```
>          # First (implicit) input + 1
 L         # Create a range [1, n]
  ʒ        # Filter; only keep elements where:
   ¹s%     #  The first input modulo this value
      Q    #  Equals the second (implicit) input

```
> 0 votes

# Answer
# Java 8, 26 bytes

```
a->b->a-b>b?a-b:a==b?a+1:0

```

Port of *@Epicness*' C# answer, after I golfed it a bit more.

Try it online.
> 0 votes

# Answer
# \>\<\>, 21 bytes

Same trick as most posted solutions. First, we prepare all necessary values on the stack and then check the comparisons.

```
::r::{-:{)?nr=?!;1+n;

```

Try it online!
> 0 votes

# Answer
# Whispers v2, 128 bytes

```
> Input
> Input
>> 1²
>> (3]
>> 1%L
>> L=2
>> Each 5 4
>> Each 6 7
>> L⋅R
>> Each 9 4 8
> {0}
>> {10}
>> 12∖11
>> Output 13

```

Try it online!

Returns a set of all possible solutions, and the empty set (i.e. \\$\emptyset\\$) when no solution exists.

## How it works

Unsurprisingly, it works almost identically to most other answers: it generates a list of numbers and checks each one for inverse modulus with the argument.

If you're familiar with how Whispers' program structure works, feel free to skip ahead to the horizontal line. If not: essentially, Whispers works on a line-by-line reference system, starting on the final line. Each line is classed as one of two options. Either it is a **nilad line**, or it is a **operator line**.

Nilad lines start with `>`, such as `> Input` or `> {0}` and return the exact value represented on that line i.e `> {0}` returns the set \\$\\{0\\}\\$. `> Input` returns the next line of STDIN, evaluated if possible.

Operator lines start with `>>`, such as `>> 1²` or `>> (3]` and denote running an operator on one or more values. Here, the numbers used do not reference those explicit numbers, instead they reference the value on that line. For example, `²` is the square command (\\$n \to n^2\\$), so `>> 1²` does not return the value \\$1^2\\$, instead it returns the square of line **1**, which, in this case, is the first input.

Usually, operator lines only work using numbers as references, yet you may have noticed the lines `>> L=2` and `>> L⋅R`. These two values, `L` and `R`, are used in conjunction with `Each` statements. `Each` statements work by taking two or three arguments, again as numerical references. The first argument (e.g. `5`) is a reference to an operator line used a function, and the rest of the arguments are arrays. We then iterate the function over the array, where the `L` and `R` in the function represent the current element(s) in the arrays being iterated over. As an example:

Let \\$A = \[1, 2, 3, 4\]\\$, \\$B = \[4, 3, 2, 1\]\\$ and \\$f(x, y) = x + y\\$. Assuming we are running the following code:

```
> [1, 2, 3, 4]
> [4, 3, 2, 1]
>> L+R
>> Each 3 1 2

```

We then get a demonstration of how `Each` statements work. First, when working with two arrays, we zip them to form \\$C = \[(1, 4), (2, 3), (3, 2), (4, 1)\]\\$ then map \\$f(x, y)\\$ over each pair, forming our final array \\$D = \[f(1, 4), f(2, 3), f(3, 2), f(4, 1)\] = \[5, 5, 5, 5\]\\$

Try it online!

---

**How *this* code works**

Working counter-intuitively to how Whispers works, we start from the first two lines:

```
> Input
> Input

```

This collects our two inputs, lets say \\$x\\$ and \\$y\\$, and stores them in lines **1** and **2** respectively. We then store \\$x^2\\$ on line **3** and create a range \\$A := \[1 ... x^2\]\\$ on line **4**. Next, we jump to the section

```
>> 1%L
>> L=2
>> Each 5 4
>> Each 6 7

```

The first thing executed here is line **7**, `>> Each 5 4`, which iterates line **5** over line **4**. This yields the array \\$B := \[i \\: \\% \\: x \\: | \\: i \in A\]\\$, where \\$a \\: \\% \\: b\\$ is defined as the modulus of \\$a\\$ and \\$b\\$.

We then execute line **8**, `>> Each 6 7`, which iterates line **6** over \\$B\\$, yielding an array \\$C := \[(i \\: \\% \\: x) = y \\: | \\: i \in A\]\\$.

For the inputs \\$x = 5, y = 2\\$, we have \\$A = \[1, 2, 3, ..., 23, 24, 25\]\\$, \\$B = \[0, 1, 2, 1, 0, 5, 5, ..., 5, 5\]\\$ and \\$C = \[0, 0, 1, 0, 0, ..., 0, 0\]\\$

We then jump down to

```
>> L⋅R
>> Each 9 4 8

```

which is our example of a dyadic `Each` statement. Here, our function is line **9** i.e `>> L⋅R` and our two arrays are \\$A\\$ and \\$C\\$. We multiply each element in \\$A\\$ with it's corresponding element in \\$C\\$, which yields an array, \\$E\\$, where each element works from the following relationship:

$$E\_i = \begin{cases} 0 & C\_i = 0 \\ A\_i & C\_i = 1 \end{cases}$$

We then end up with an array consisting of \\$0\\$s and the inverse moduli of \\$x\\$ and \\$y\\$. In order to remove the \\$0\\$s, we convert this array to a set (`>> {10}`), then take the set difference between this set and \\$\\{0\\}\\$, yielding, then outputting, our final result.
> 0 votes

# Answer
**C#, 53 bytes (83 with function heading)**

```
static int F(int a, int b){
    for(int i=1;i<=a+1;i++){if(a%i==b)return i;}return 0;
}

```

Try It Online

First try at codegolf. Probably not the best language to use, nor the most efficient coding.
> -1 votes

---
Tags: code-golf, math, number-theory
---


title: Trim that distracting background off!

text:
# Question
Title: Trim that distracting background off!
Isn't it annoying when you're taking a picture, but the background detracts from the actual substance of the image? I'd say it is. I need to know how much I should crop so that I get rid of this problem! But - as usual - I am quite lazy, so I need someone to do this for me...

## Task & Rules

Given a binary matrix representing the image, output the dimensions (width and height) of the smallest sub-matrix that contains all the \\$1\\$s in the original matrix. A *sub-matrix* is a block of adjacent entries from the original matrix. Equivalently, it is a new matrix formed by overlapping a subset of adjacent rows and a subset of adjacent columns of the original.

* It is allowed to take the width and the height of the matrix as input as well.
* The input is guaranteed to contain at least one \\$1\\$.
* You can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so try to complete the task in the least bytes you can manage in your language of choice.

## Example

$$\left\[\begin{matrix} \color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\\ \color{red}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}0\\ \color{red}0&\color{blue}1&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}1\\ \color{red}0&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0\\ \color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\end{matrix}\right\] \longrightarrow \left\[\begin{matrix}1&0&1&0&0\\1&1&0&1&1\\0&1&0&1&0\end{matrix}\right\]\longrightarrow(5,3)$$

## Test cases

```
Input | Output

[[0,1,0,0,0,1,0]]
--> (5,1) or (1,5)

[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0]]
--> (3,2) or (2,3)

[[1,1,1,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
--> (4,4)

[[0,0,0,0,0,0],[0,1,0,1,0,1],[0,0,0,0,0,0]]
--> (5,1) or (1,5)

[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[0,0,0,0,0]]
--> (3,3)

[[0,0,0,0,0,0],[0,1,0,1,0,0],[0,1,1,0,1,1],[0,0,1,0,1,0],[0,0,0,0,0,0]]
--> (5,3) or (3,5)

```

# Answer
# MATL, 5 bytes

```
JYaZy

```

Try it online! Or verify all test cases.

### Explanation

```
JYa   % Implicit input. Unpad matrix. This removes outer zeros
Zy    % Size. Implicit display

```
> 11 votes

# Answer
# Octave, ~~57 56~~ 45 bytes

Here `find` does the heavy lifting: It `finds` the row and colum indices of the nonzero entries. Then we just have to find the difference between the maximum and the minimum (plus one) for each of those seperately.

Thanks @beaker and @AndrasDeak for -1 byte, and @LuisMendo for -11 bytes!

```
@(a){[I{1:2}]=find(a),cellfun(@range,I)}{2}+1

```

Try it online!
> 5 votes

# Answer
# APL (Dyalog Unicode), 10 bytesSBCS

Anonymous tacit prefix function.

```
(1+⌈/-⌊/)⍸

```

Try it online!

indices of 1s.

`(``)` apply the following tacit function to that:

`⌊/` the minimum (lowest *y* coordinate and lowest *x* coordinate)

`⌈/-` the maximum minus that (this gives us the range)

`1+` one plus that (to be inclusive)
> 5 votes

# Answer
# Python 2, ~~92~~ 86 bytes

```
def f(a,L=len):exec"a=zip(*a[1-any(a[0]):])[::-1];"*4*L(a[0])*L(a);return L(a[0]),L(a)

```

Try it online!
> 3 votes

# Answer
# Jelly, 7 bytes

```
S,§t€0Ẉ

```

Try it online!

### How it works

```
S,§t€0Ẉ  Main link. Argument: M (matrix)

S        Take the columnwise sum. Let's call the resulting array A.
  §      Take the sum of each row. Let's call the resulting array B.
 ,       Pair; yield [A, B].
   t€0   Trim surrounding zeroes of A and B.
      Ẉ  Widths; yields the lengths of the trimmed arrays.

```
> 3 votes

# Answer
# Python 2,  ~~63~~  55 bytes

-8 with help from Vincent (take the input matrix as a Numpy array)

```
lambda a:[len(`a.max(x)`[7::3].strip('0'))for x in 0,1]

```

An unnamed function accepting a 2-d Numpy array of integers (in `{0,1}`) which returns a list of integers, `[width,height]`.

**Try it online!**

---

Non-Numpy version in 63 bytes (accepting a list of lists of integers in `{0,1}`):

```
lambda a:[len(`map(max,v)`[1::3].strip('0'))for v in zip(*a),a]

```

Try it online!

### How?

Given a matrix, `a`, `for` each (`v`) of the transpose, `zip(*a)`, and `a` itself we find the height required (given the transpose this is the width).

Mapping `max` across `v` yields a list of zeros and ones, representing if each row of `v` contains any ones. The string representation of this list is found using backticks (``...``), this gives a string with a leading `[`, then the zeros and ones delimited by `,`  (comma+space). We slice this string starting at index one in steps of three using `[1::3]` getting us a string of only the zeros and ones, which allows us to use the string function `strip` to remove the outer zeros (`strip('0')`).

For example:

```
      a = [[0,0,0,0,0]           map(max,a)                    = [0,1,1]
          ,[0,1,0,0,0]          `map(max,a)`[1::3]             = '011'
          ,[0,0,0,1,0]]         `map(max,a)`[1::3].strip('0')  = '11'
                            len(`map(max,a)`[1::3].strip('0')) = 2

zip(*a) = [(0,0,0)         map(max,zip(*a))                    = [0,1,0,1,0]
          ,(0,1,0)        `map(max,zip(*a))`[1::3]             = '01010'
          ,(0,0,0)        `map(max,zip(*a))`[1::3].strip('0')  = '101'
          ,(0,0,1)    len(`map(max,zip(*a))`[1::3].strip('0')) = 3
          ,(0,0,0)]

    --> [len(`map(max,v)`[1::3].strip('0'))for v in zip(*a),a] = [3,2]

```
> 3 votes

# Answer
# Retina 0.8.2, 83 bytes

```
+`^0+¶|¶0+$

+1`((.)*).(¶(?<-2>.)*).(?<=(1)¶.*|(.))
$1$3$4$5
(¶?)*0*(.*1)0*
$#1 $.2

```

Try it online! Explanation:

```
+`^0+¶|¶0+$

```

Delete leading and trailing zero rows.

```
+1`((.)*).(¶(?<-2>.)*).(?<=(1)¶.*|(.))
$1$3$4$5

```

Remove all `0`s on the lines above the last. Remove all the `1`s two, but change the digit underneath on the next line to a `1` in that case. This bitwise or's the rows together.

```
(¶?)*0*(.*1)0*
$#1 $.2

```

Count the number of rows as the number of newlines plus 1 and the number of columns as the number of digits between the first and last 1.
> 1 votes

# Answer
# , 31 bytes

```
[:$([:|.@|:}.^:(0=1#.{.))^:4^:_

```

Try it online!

## Explanation:

```
                            ^:_ - repeat until the result stops changing
   (                    )^:4    - repeat 4 times
             ^:(        )       - is
                  1#.           - the sum of
                      {.        - the first row
                 =              - equal
                0               - to 0
           }.                   - if yes, drop the first row
    [:|.@|:                     - transpose and reverse (rotate 90 degrees)
[:$                             - what's the shape of the result?

```
> 1 votes

# Answer
# q/kdb+, 16 bytes

```
sum@'(|/;|/')@\:

```
> 1 votes

# Answer
# Mathematica, 34 bytes

```
Max@#-Min@#+1&/@(#~Position~1)&

```

Pure function. Takes a nested list of integers as input, and returns a list of two integers (the height followed by the width) as output. The Unicode character is U+F3C7 for `\[Transpose]`.
> 1 votes

# Answer
# , ~~48~~ 46 bytes

```
function(m)1+diff(apply(which(m>0,T),2,range))

```

Try it online!

-2 bytes saved by Giuseppe.
> 1 votes

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

```
ζ‚Oε0Û0Üg

```

-2 bytes thanks to *@Mr.Xcoder*.

Try it online or verify all test cases.

**Explanation:**

```
ζ            # Swap the rows and columns of the (implicit) input-list
 ‚           # Pair it with the (implicit) input-list
  O          # Take the sum of each column and row
   ε         # Map Both the list of column-sums and list of row-sums to:
    0Û       #  Remove all leading zeros
      0Ü     #  Remove all trailing zeros
        g    #  Take the length of the remaining lists

```
> 1 votes

# Answer
# Japt, ~~16~~ 15 bytes

```
[UUy]®=ðd)ÎaZÌÄ

```

Try it or run all test cases

---

## Explanation

```
[   ]               :Create an array containing
 U                  : The input and
  Uy                : The input transposed
     ®              :Map each Z
       ð            : Indices of elements where
        d           :  Any element is truthy (not 0)
      =  )          : Reassign to Z
          Î         : First element
           a        : Absolute difference with
            ZÌ      :  Last element
              Ä     :   Plus 1

```
> 0 votes

# Answer
# Jelly, 9 bytes

```
ŒṪZṀ_ṂƊ€‘

```

Try it online!
> 0 votes

# Answer
# Haskell, 76 bytes

```
f x=length.s.reverse.s<$>[foldr(zipWith(:))e x,x]
e=[]:e
s=snd.span(all(<1))

```

Try it online!
> 0 votes

# Answer
# Ruby, 60 bytes

```
->m{[m,m.transpose].map{|x|x.map(&:max).join[/1.*/]=~/0*$/}}

```

Try it online!
> 0 votes

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


title: Array Merge without Duplicates

text:
# Question
Title: Array Merge without Duplicates
I recently saw this Javascript code on StackOverflow for merging two arrays, and removing duplicates:

```
Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }
    return a;
};

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2).unique();

```

While this code works, it is horribly inefficient (`O(n^2)`). Your challenge is to make an algorithm with less complexity.

The winning criteria is the solution with the least complexity, but ties will be broken by shortest length in characters.

**Requirements**:

Package all your code together in a function that meets the following requirements for "correctness:"

* Input: Two arrays
* Output: One array
* Merges elements of both arrays together- Any element in either input array must be in the outputted array.
* **The outputted array should have no duplicates.**
* Order doesn't matter (unlike the original)
* Any language counts
* **Don't use the standard library's array functions for detecting uniqueness or merging sets/arrays** (although other things from the standard library is okay). Let me make the distinction that array concatenation is fine, but functions that already do all of the above are not.

# Answer
# Perl

## 27 Characters

Simple Perl Hack

```
my @vals = ();
push @vals, @arr1, @arr2;
my %out;
map { $out{$_}++ } @vals;
my @unique = keys %out;

```

I'm sure someone could one-liner this.. and thus (Thanks Dom Hastings)

```
sub x{$_{$_}++for@_;keys%_}

```
> 8 votes

# Answer
# JavaScript O(N) 131 124 116 92 (86?)

Golfed version:

```
function m(i,x){h={};n=[];for(a=2;a--;i=x)i.map(function(b){h[b]=h[b]||n.push(b)});return n}

```

Human readable golfed version:

```
function m(i,x) {
   h = {}
   n = []
   for (a = 2; a--; i=x)
      i.map(function(b){
        h[b] = h[b] || n.push(b)
      })
   return n
}

```

I could use `concat` like so and do it in 86 characters:

```
function m(i,x){h={};n=[];i.concat(x).map(function(b){h[b]=h[b]||n.push(b)});return n}

```

But I am not sure if it is still O(N) based on this JsPerf: http://jsperf.com/unique-array-merging-concat-vs-looping as the concat version is marginally faster with smaller arrays but slower with larger arrays (Chrome 31 OSX).

In practice do this (golf is full of bad practices):

```
function merge(a1, a2) {
   var hash = {};
   var arr = [];
   for (var i = 0; i < a1.length; i++) {
      if (hash[a1[i]] !== true) {
        hash[a1[i]] = true;
        arr[arr.length] = a1[i];
      }
   }
   for (var i = 0; i < a2.length; i++) {
      if (hash[a2[i]] !== true) {
        hash[a2[i]] = true;
        arr[arr.length] = a2[i];
      }
   }
   return arr;
}
console.log(merge([1,2,3,4,5],[1,2,3,4,5,6]));

```

I'm not great at computing complexity but I believe this is `O(N)`. Would love if someone could clarify.

**Edit:** Here is a version that takes any number of arrays and merges them.

```
function merge() {
   var args = arguments;
   var hash = {};
   var arr = [];
   for (var i = 0; i < args.length; i++) {
      for (var j = 0; j < args[i].length; j++) {
        if (hash[args[i][j]] !== true) {
          arr[arr.length] = args[i][j];
          hash[args[i][j]] = true;
        }
      }
    }
   return arr;
}
console.log(merge([1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8]));

```
> 10 votes

# Answer
## Python 2.7, 38 chars

```
F=lambda x,y:{c:1 for c in x+y}.keys()

```

Should be O(N) assuming a good hash function.

Wasi's 8 character `set` implementation is better, if you don't think it violates the rules.
> 4 votes

# Answer
**PHP, 69/42 68/41 chars**

Including the function declaration is 68 characters:

```
function m($a,$b){return array_keys(array_flip($a)+array_flip($b));}

```

Not including the function declaration is 41 characters:

```
array_keys(array_flip($a)+array_flip($b))

```
> 4 votes

# Answer
### One way in Ruby

To keep within the rules outlined above, I would use a similar strategy as the JavaScript solution and use a hash as an intermediary.

```
merged_arr = {}.tap { |hash| (arr1 + arr2).each { |el| hash[el] ||= el } }.keys

```

Essentially, these are the steps I'm going through in the line above.

1. Define a variable `merged_arr` that will contain the result
2. Initialize an empty, unnamed hash as an intermediary to put unique elements in
3. Use `Object#tap` to populate the hash (referenced as `hash` in the `tap` block) and return it for subsequent method chaining
4. Concatenate `arr1` and `arr2` into a single, unprocessed array
5. For each element `el` in the concatenated array, put the value `el` in `hash[el]` if no value of `hash[el]` currently exists. The memoization here (`hash[el] ||= el`) is what ensures the uniqueness of elements.
6. Fetch the keys (or values, as they are the same) for the now populated hash

This should run in `O(n)` time. Please let me know if I've made any inaccurate statements or if I can improve the above answer either for efficiency or readability.

### Possible improvements

Using memoization is probably unnecessary given that the keys to the hash are going to be unique and the values are irrelevant, so this is sufficient:

```
merged_arr = {}.tap { |hash| (arr1 + arr2).each { |el| hash[el] = 1 } }.keys

```

I really love `Object#tap`, but we can accomplish the same result using `Enumerable#reduce`:

```
merged_arr = (arr1 + arr2).reduce({}) { |arr, val| arr[val] = 1; arr }.keys

```

You could even use `Enumberable#map`:

```
merged_arr = Hash[(arr1 + arr2).map { |val| [val, 1] }].keys

```

### How I would do it in practice

Having said all that, if I were asked to merge two arrays `arr1` and `arr2` such that the result `merged_arr` has unique elements and could use any Ruby method at my disposal, I would simply use the set union operator which is intended for solving this exact problem:

```
merged_arr = arr1 | arr2

```

A quick peek at the source of `Array#|`, though, seems to confirm that using a hash as an intermediary seems to be the acceptable solution to performing a unique merge between 2 arrays.
> 3 votes

# Answer
```
Array.prototype.unique = function()
{
  var o = {},i = this.length
  while(i--)o[this[i]]=true
  return Object.keys(o)
}

```

A function that would take n arrays could be the following:

```
function m()
{
  var o={},a=arguments,c=a.length,i;
  while(c--){i=a[c].length;while(i--)o[a[c][i]] = true}
  return Object.keys(o);
}

```

Golfed, I think this should work ( 117 chars )

```
function m(){var o={},a=arguments,c=a.length,i;while(c--){i=a[c].length;while(i--)o[a[c][i]]=1}return Object.keys(o)}

```

**Update** If you want to keep the original type, you could

```
function m()
{
  var o={},a=arguments,c=a.length,f=[],g=[];
  while(c--)g.concat(a[c])
  c = g.length
  while(c--){if(!o[g[c]]){o[g[c]]=1;f.push(g[c])}}
  return f
}

```

or golfed 149:

```
function m(){var o={},a=arguments,c=a.length,f=[],g=[];while(c--)g.concat(a[c]);c= g.length;while(c--){if(!o[g[c]]){o[g[c]]=1;f.push(g[c])}}return f}

```

This still can cast some doubts, if you want to distinguish `123` and `'123'`, then this would not work..
> 2 votes

# Answer
## Mathematica 10 Chars

```
Union[a,b]

```

Example:

```
a={1,2,3,4,5};
b={1,2,3,4,5,6};
Union[a,b]

```

> {1, 2, 3, 4, 5, 6}

## Mathematica2 43 Chars

```
Sort@Join[a, b] //. {a___, b_, b_, c___} :> {a, b, c}

```
> 2 votes

# Answer
## python,46

```
def A(a,b):print[i for i in b if i not in a]+a

```

Or, using set operation simply

## python, 8

```
set(a+b)

```
> 2 votes

# Answer
## Fortran: 282 252 233 213

Golfed version:

```
function f(a,b,m,n) result(d);integer::m,n,a(m),b(n),c(m+n);integer,allocatable::d(:);j=m+1;c(1:m)=a(1:m);do i=1,n;if(.not.any(b(i)==c(1:m)))then;c(j)=b(i);j=j+1;endif;enddo;allocate(d(j-1));d=c(1:j-1);endfunction

```

Which not only looks infinitely better but will actually compile (too long a line in its golfed form) with the human-readable form:

```
function f(a,b,m,n) result(d)
  integer::m,n,a(m),b(n),c(m+n)
  integer,allocatable::d(:)
  j=m+1;c(1:m)=a(1:m)
  do i=1,n
     if(.not.any(b(i)==c(1:m)))then
        c(j)=b(i);j=j+1
     endif
  enddo
  allocate(d(j-1))
  d=c(1:j-1)
end function

```

This should be `O(n)` as I copy `a` into `c` and then check each `b` against all of `c`. The last step is to eliminate the garbage that `c` will contain since it is uninitialized.
> 2 votes

# Answer
# Perl

23 bytes, if we only count the code block inside subroutine. Could be 21, if overwriting global values is allowed (it would remove `my` from the code). It returns elements in random order, because order doesn't matter. As for complexity, on average it's O(N) (depends on number of hash collisions, but they are rather rare - in worst case it can be O(N2) (but this shouldn't happen, because Perl can detect pathological hashes, and changes the hash function seed when it detects such behavior)).

```
use 5.010;
sub unique{
    my%a=map{$_,1}@_;keys%a
}
my @a1 = (1, 2, 3, 4);
my @a2 = (3, 4, 5, 6);
say join " ", unique @a1, @a2;

```

Output (also showing randomness):

```
/tmp $ perl unique.pl
2 3 4 6 1 5
/tmp $ perl unique.pl
5 4 6 2 1 3

```
> 2 votes

# Answer
**Javascript 86**

Golfed version:

```
function m(a,b){var h={};return a.concat(b).filter(function(v){return h[v]?0:h[v]=1})}

```

Readable version:

```
function merge(a, b) {
  var hash = {};
  return a.concat(b).filter(function (val) {
    return hash[val] ? 0 : hash[val] = 1;
  });
}

```
> 1 votes

# Answer
## JavaScript 60

I'm using ES6 generator.
The following is testable using Google's Traceur REPL.

```
m=(i,j)=>{h={};return[for(x of i.concat(j))if(!h[x])h[x]=x]}

```
> 1 votes

# Answer
If you're looking for a JavaScript-based implementation that relies on the underlying Objects behind the framework to be efficient, I would've just used Set. Usually in an implementation, the Set object inherently handles unique objects during insertion with some sort of binary search indexing. I know in Java it's a `log(n)` search, using binary search based on the fact that no set can contain a single object more than once.

---

While I have no idea if this is also true for Javascript, something as simple as the following snippet may suffice for an `n*log(n)` implementation:

# JavaScript, 61 bytes

```
var s = new Set(a);      // Complexity O(a.length)
b.forEach(function(e) {  // Complexity O(b.length) * O(s.add())
  s.add(e);
});

```

Try it online!

---

If the above snippet uses `a = [1,2,3]` and `b = [1,2,3,4,5,6]` then `s=[1,2,3,4,5,6]`.

If you know the complexity of the `Set.add(Object)` function in JavaScript let me know, the complexity of this is `n + n * f(O)` where `f(O)` is the complexity of `s.add(O)`.
> 0 votes

# Answer
# APL (Dyalog Unicode), O(N), 28 bytes

Anonymous tacit infix function.

```
(⊢(/⍨)⍳∘≢=⍳⍨),

```

Try it online!

`,` concatenate the arguments; O(N)

`(``)` apply the following anonymous tacit function on that; O(1)

`⍳⍨` indices selfie (indices of first occurrence of each element in the entire array); O(N)

`=` compare element by element to; O(N):

`⍳∘≢` indices of the length of the array; O(N)

`(/⍨)` use that to filter; O(N):

the unmodified argument; O(1)

O(N + 1 + N + N + N + N + 1) = O(N)
> 0 votes

---
Tags: fastest-algorithm
---


title: convert decimal to duodecimal

text:
# Question
Title: convert decimal to duodecimal
The task is to convert a string representing a number in decimal (base 10) representation to duodecimal (base 12). The input is thus a string, the output should be printed.

The input number can be positive and negative, can be integer or rational. The decimal and duodecimal representations will have a finite number of digits after the (duo)decimal point.

The digits for duodecimal should be 0-9, a, b.

The output should not contain trailing zeroes after the duodecimal point and no leading zeroes before the duodecimal point. The duodecimal point should only be printed if the number is non-integer.

## examples

input 400 -\> output 294

input 14 -\> output 12

input 1498 -\> output a4a

input -11 -\> output -b

input 11.875 -\> output b.a6

## counter examples

not okay are outputs like "-001a", "00b.300", "1.050".

## EDIT: additional assumptions

* the number can be represented exactly as float
* there are overall less than 7 digits (excluding a minus and a duodecimal point) needed to represent the result.

# Answer
> 3 votes
# Japt, 2 bytes

I feel I must be missing something ...

```
sC

```

Try it

# Answer
> 3 votes
# C (~~137~~ 134 bytes)

(thanks for the help Kevin Cruijssen)

```
l=144;main(b,w){float v;scanf("%f",&v);w=v*l*12;for(w<0&&printf("-",w=-w);b<w;b*=12);for(;(b/=12)>l|w;w%=b)printf(".%x"+(b!=l),w/b);}

```

Explanation:

Pretty much just an implementation of the base-conversion. This is the algorithm in a readable form:

```
int main() {
    float v;
    int b, w;
    scanf("%f",&v);
    w=v*1728; // Multiply with 1728, so we can use int-arithmetic
    // Deal with the sign
    if (w<0) {
        printf("-");
        w=-w;
    }
    // Find largest power of 12 we care about
    while (b<w) {
        b*=12;
    }
    // At b == 1728 the fractional part starts.
    while(b > 1728 || w != 0) {
        b /= 12;
        if (b == 1728) {
            printf(".");
        }
        printf("%x",w/b);
        w = w % b;
    }
}

```

This is then golfed down with fairly standard C-tricks:

* Symbols without a type are assumed int.
* Use arguments to main to save variable declarations.
* First argument to main is initialized to 1 (argc).
* Use binary operators instead of control-flow structures.
* The branch in the main loop can be removed by instead calculating an index into a single format-string.
* Shuffle around some statements and side-effects to save a character here-and-there.
* Store 144 into a variable, to not type out that constant so often (the shuffling in the previous step makes 144 a better candidate than 1728).

My personal favorite is probably the `w<0&&printf("-",w=-w)` part, even though it only saves a character or two compared to the next obvious way - by putting the `w=-w` as an (unused) argument to printf, we save some parenthesis that would otherwise be needed to group two side-effects into a single expression.

# Answer
> 2 votes
# Perl 6, 20 bytes

```
(+*).base(12).lc.say

```

Try it online!

The built-in `base` method on numbers just does the right thing, including for negative numbers and floats. However, it outputs letters as uppercase, so the `lc` method call fixes that.

# Answer
> 0 votes
# PHP, 96 bytes

It´s lengthy with the decimals, but quite simple with the limited number of digits.

```
<?="0-"[0<=>$argn],trim(substr($r=base_convert($argn*12**6,10,12),0,-6).".".substr($r,-6),".0");

```

Save to file, run as pipe with `-F`

requires PHP 7.0:
older PHP has no spaceship or power operators → parse error
PHP 7.1 understands negative string indexes → negative output for positive input

To fix:
Replace `"0-"[0<=>$argn]` with `"-"[$argn>=0]` and insert `?:0` before `;`. (→97 bytes)
For PHP 5.5, additionaly replace `12**6` with `2985984`. (→99 bytes)
For PHP 5.3 or 5.4, additionally replace the part before the first comma with `$argn<0?"-":""`. (→100 bytes)
For older PHP, use `<?=($r=trim(...))?$argn>0?$r:"-$r":0;` (→103 bytes)

**breakdown**

```
<?=                             # PHP: echo
"0-"[0<=>$argn],                # 1. print minus (dumped by base_convert) or zero (dumped by trim)
trim(
    substr(
        $r=base_convert(
            $argn*12**6         # 2. multiply input with 6**12
        ,10,12)                 # 3. convert to duodecimal
    ,0,-6)                      # 4. first digits are integer part
    .".".substr($r,-6)          # 5. last 6 digits are fraction
,".0")                          # 6. trim: crop by zeroes and point
;

```

# Answer
> 0 votes
# ZSH with extendedglob, 81 bytes

```
read l;r=$(([##12]l*12**6));s=${(L)r[1,-7]}.${(L)r[-6,-1]%%0##};echo - ${s%.}

```

save to file and run in pipe `echo "400" | zsh convert.sh`

```
read l         # read from stdin

# $(())        arithmetic mode
# l*12**6      multiply the number by 12^6 (base change can't handle stuff after the decimal point)
# [#12]        print it in base 12
# [##12]       same, without the leading base modifier printed
r=$(([##12]l*12**6));

# (L)          convert letters to lower case
# [1,-7]       pick all but the last 6 characters
# :-0          if these are empty, print 0 instead
# [-6,-1]      and the last 6 characters, respectively
# %            remove the largest trailing match ...
# %%           same, but largest match
# 0##          pattern is an arbitrary amount of zeroes
# .            print a . between the two blocks
s=${(L)r[1,-7]:-0}.${(L)r[-6,-1]%%0##}

# %.           remove trailing .
# -            avoid interpreting a possible minus sign as option
echo - ${s%.}

```

# Answer
> 0 votes
# JS, 17 bytes

```
a=>a.toString(12)

```

When run in the console, Javascript implicitly outputs the result.

# Answer
> 0 votes
# 05AB1E, 29 bytes

```
Ä6xsm*12BR6ô'.ýR0Ü'.ÜlI0‹i'-ì

```

Very ugly and long, but it works.. Both the decimals and negative aren't supported during base conversion in 05AB1E, so I have to do things manually..

Try it online or verify all test cases.

**Explanation:**

```
Ä                # Take the absolute value of the (implicit) input
                 #  i.e. -11.875 → 11.875
 6x              # Push 6 and 6 doubled (so 12)
   sm            # Swap them, and take the power of each other: 6**12 → 2985984
     *           # Multiply it by the absolute value of the input
                 #  i.e. 2985984 * 11.875 → 35458560.0
      12B        # Convert it to Base-12:
                 #  i.e. 35458560.0 → "BA60000"
R                # Reverse it
                 #  i.e. "BA60000" → "00006AB"
 6ô              # Split it into chunks of size 6
                 #  i.e. "00006AB" → ["00006A","B"]
   '.ý          '# Join the list by "."
                 #  i.e. ["00006A","B"] → "00006A.B"
      R          # Reverse it back
                 #  i.e. "00006A.B" → "B.A60000"
       0Ü        # Remove any trailing zeros
                 #  i.e. "B.A6"
         '.Ü    '# Then remove any trailing dots
                 #  i.e. "B.A6" remains "B.A6"
                 #  i.e. "294." → "294"
            l    # And convert it to lowercase
                 #  i.e. "B.A6" → "b.a6"
I0‹i             # If the input is smaller than 0:
                 #  i.e. -11.875 → 1 (truthy)
    '-ì         '# Prepend a "-"
                 #  i.e. "b.a6" → "-b.a6"
                 # (And output the top of the stack implicitly as result)

```

---
Tags: code-golf, base-conversion
---