title: Lossy ASCII art compression

text:
# Question
Title: Lossy ASCII art compression
### Background

PICASCII is a neat tool that converts images into ASCII art.

It achieves different degrees of brightness by using the following ten ASCII characters:

```
@#+';:,.`

```

We'll say that these charxels (character elements) have brightnesses from 1 (at-sign) to 10 (space).

Below, you can see the results of converting a little code, the Welsh flag, an overhanded fractal, a large trout and a little golf, displayed with the correct font:

Your can see the images in this fiddle and download them from Google Drive.

### Task

While the end results of PICASCII are visually pleasing, all five images combined weigh 153,559 bytes. How much could these images be compressed if we are willing to sacrifice part of their quality?

Your task is to write a program that accepts an ASCII art image such as the above ones and a minimum quality as input and prints a lossy compression of the image – in form of a full program or a function returning a single string – that satisfies the quality requirement.

**This means that you do not get to write a separate decompressor; it must be built-in into each of the compressed images.**

The original image will consist of charxels with brightnesses between 1 and 10, separated by linefeeds into lines of the same length. The compressed image must have the same dimensions and use the same set of characters.

For an uncompressed image consisting of **n** charxels, the quality of a compressed version of the image is defined as

where **ci** is the brightness of the **i**th charxel of the compressed image's output and **ui** the brightness of the **i**th charxel of the uncompressed image.

### Scoring

Your code will be run with the five images from above as input and minimum quality settings of 0.50, 0.60, 0.70, 0.80 and 0.90 for each of the images.

Your score is the geometric mean of the sizes of all compressed images, i.e., the twenty-fifth root of the product of the lengths of all twenty-five compressed images.

The lowest score wins!

### Additional rules

* Your code has to work for arbitrary images, not just the ones used for scoring.

It is expected that you optimize your code towards the test cases, but a program that does not even *attempt* to compress arbitrary images won't get an upvote from me.
* Your compressor may use built-in byte stream compressors (e.g., gzip), but you have to implement them yourself for the compressed images.

Bulit-ins normally used in byte stream decompressors (e.g., base conversion, run-length decoding) are allowed.
* Compressor and compressed images do not have to be in the same language.

However, you must pick a single language for all compressed images.
* For each compressed image, standard code golf rules apply.

### Verification

I've made a CJam script to easily verify all quality requirements and calculate a submission's score.

You can download the Java interpreter from here or here.

```
e# URLs of the uncompressed images.
e# "%s" will get replaced by 1, 2, 3, 4, 5.

"file:///home/dennis/codegolf/53199/original/image%s.txt"

e# URLs of the compressed images (source code).
e# "%s-%s" will get replaced by "1-50", "1-60", ... "5-90".

"file:///home/dennis/codegolf/53199/code/image%s-%s.php"

e# URLs of the compressed images (output).

"file:///home/dennis/codegolf/53199/output/image%s-%s.txt"

e# Code

:O;:C;:U;5,:)
{
    5,5f+Af*
    {
        C[IQ]e%g,X*:X;
        ISQS
        [U[I]e%O[IQ]e%]
        {g_W=N&{W<}&}%
        _Nf/::,:=
        {
            {N-"@#+';:,.` "f#}%z
            _::m2f#:+\,81d*/mq1m8#
            _"%04.4f"e%S
            @100*iQ<"(too low)"*
        }{
            ;"Dimension mismatch."
        }?
        N]o
    }fQ
}fI
N"SCORE: %04.4f"X1d25/#e%N

```

### Example

> ### Bash → PHP, score 30344.0474
>
> ```
> cat
>
> ```
>
> Achieves 100% quality for all inputs.
>
> ```
> $ java -jar cjam-0.6.5.jar vrfy.cjam
> 1 50 1.0000
> 1 60 1.0000
> 1 70 1.0000
> 1 80 1.0000
> 1 90 1.0000
> 2 50 1.0000
> 2 60 1.0000
> 2 70 1.0000
> 2 80 1.0000
> 2 90 1.0000
> 3 50 1.0000
> 3 60 1.0000
> 3 70 1.0000
> 3 80 1.0000
> 3 90 1.0000
> 4 50 1.0000
> 4 60 1.0000
> 4 70 1.0000
> 4 80 1.0000
> 4 90 1.0000
> 5 50 1.0000
> 5 60 1.0000
> 5 70 1.0000
> 5 80 1.0000
> 5 90 1.0000
>
> SCORE: 30344.0474
>
> ```

# Answer
# Java → CJam, score ≈4417.89

```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.aditsu.cjam.CJam;

public class Compress {
    protected static final char[] DIGITS = "0123456789ABCDEFGHIJK".toCharArray();
    protected static final String CHARS = "@#+';:,.` ";
    protected static final char[] CHR = CHARS.toCharArray();

    private static class Img {
        public final int rows;
        public final int cols;
        public final int[][] a;

        public Img(final int rows, final int cols) {
            this.rows = rows;
            this.cols = cols;
            a = new int[rows][cols];
        }

        public Img(final List<String> l) {
            rows = l.size();
            cols = l.get(0).length();
            a = new int[rows][cols];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    a[i][j] = CHARS.indexOf(l.get(i).charAt(j));
                }
            }
        }

        public static Img read(final Reader r) {
            try {
                final BufferedReader br = new BufferedReader(r);
                final List<String> l = new ArrayList<>();
                while (true) {
                    final String s = br.readLine();
                    if (s == null || s.isEmpty()) {
                        break;
                    }
                    l.add(s);
                }
                br.close();
                return new Img(l);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public static Img read(final File f) {
            try {
                return read(new FileReader(f));
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public Img scaleDown(final int fr, final int fc) {
            final int r1 = (rows + fr - 1) / fr;
            final int c1 = (cols + fc - 1) / fc;
            final Img x = new Img(r1, c1);
            final int[][] q = new int[r1][c1];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[i / fr][j / fc] += a[i][j];
                    q[i / fr][j / fc]++;
                }
            }
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] /= q[i][j];
                }
            }
            return x;
        }

        public Img scaleUp(final int fr, final int fc) {
            final int r1 = rows * fr;
            final int c1 = cols * fc;
            final Img x = new Img(r1, c1);
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] = a[i / fr][j / fc];
                }
            }
            return x;
        }

        public Img crop(final int r, final int c) {
            if (r == rows && c == cols) {
                return this;
            }
            final Img x = new Img(r, c);
            for (int i = 0; i < r; ++i) {
                for (int j = 0; j < c; ++j) {
                    x.a[i][j] = a[i][j];
                }
            }
            return x;
        }

        public Img rescale(final int fr, final int fc) {
            return scaleDown(fr, fc).scaleUp(fr, fc).crop(rows, cols);
        }

        public double quality(final Img x) {
            if (x.rows != rows || x.cols != cols) {
                throw new IllegalArgumentException();
            }
            double t = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    final int y = a[i][j] - x.a[i][j];
                    t += y * y;
                }
            }
            t /= 81 * rows * cols;
            t = 1 - Math.sqrt(t);
            return Math.pow(t, 8);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    sb.append(CHR[a[i][j]]);
                }
                sb.append('\n');
            }
            return sb.toString();
        }

        public Array toArray() {
            final Array x = new Array(rows * cols);
            int k = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[k++] = a[i][j];
                }
            }
            return x;
        }

        public String compress(final double quality) {
            int bi = 1;
            int bj = 1;
            int bs = rows * cols;
            Img bx = this;

            for (int i = 1; i < 3; ++i) {
                for (int j = 1; j < 3; ++j) {
                    Img x = rescale(i, j);
                    if (quality(x) >= quality) {
                        x = scaleDown(i, j);
                        if (x.rows * x.cols < bs) {
                            bi = i;
                            bj = j;
                            bs = x.rows * x.cols;
                            bx = x;
                        }
                    }
                }
            }

            Array a = bx.toArray();
            int bf = 0;
            for (int i = 1; i <= 20; ++i) {
                final int t = a.rle11(i).n;
                if (t < bs) {
                    bs = t;
                    bf = i;
                }
            }

            int b = 10;
            if (bf > 0) {
                b = 11;
                a = a.rle11(bf);
            }

            String s = null;
            for (int i = 92; i < 97; ++i) {
                for (char c = ' '; c < '$'; ++c) {
                    final String t = a.cjamBase(b, i, c);
                    boolean ok = true;
                    for (int j = 0; j < t.length(); ++j) {
                        if (t.charAt(j) > '~') {
                            ok = false;
                            break;
                        }
                    }
                    if (!ok) {
                        continue;
                    }
                    if (s == null || t.length() < s.length()) {
                        s = t;
                    }
                }
            }

            if (bf > 0) {
                s += "{(_A={;()";
                if (bf > 1) {
                    s += DIGITS[bf] + "*";
                }
                s += "\\(a@*}&\\}h]e_";
            }
            if (bi * bj == 1) {
                return s + '"' + CHARS + "\"f=" + cols + "/N*";
            }
            s += bx.cols + "/";
            if (bi > 1) {
                s += bi + "e*";
                if (rows % 2 == 1) {
                    s += "W<";
                }
            }
            if (bj > 1) {
                s += bj + "fe*";
                if (cols % 2 == 1) {
                    s += "Wf<";
                }
            }
            return s + '"' + CHARS + "\"ff=N*";
        }

        public void verify(final String s, final double quality) {
            final String t = CJam.run(s, "");
            final Img x = read(new StringReader(t));
            final double q = quality(x);
            if (q < quality) {
                throw new RuntimeException(q + " < " + quality);
            }
//          System.out.println(q + " >= " + quality);
        }
    }

    private static class Array {
        public final int[] a;
        public final int n;

        public Array(final int n) {
            this.n = n;
            a = new int[n];
        }

        public Array(final int[] a) {
            this.a = a;
            n = a.length;
        }

        public String join() {
            final StringBuilder sb = new StringBuilder();
            for (int x : a) {
                sb.append(x).append(' ');
            }
            sb.setLength(sb.length() - 1);
            return sb.toString();
        }

//      public String cjamStr() {
//          final StringBuilder sb = new StringBuilder("\"");
//          for (int x : a) {
//              sb.append(DIGITS[x]);
//          }
//          sb.append("\":~");
//          return sb.toString();
//      }

        public String cjamBase(final int m, final int b, final char c) {
            final boolean zero = a[0] == 0;
            String s = join();
            if (zero) {
                s = "1 " + s;
            }
            s = CJam.run("q~]" + m + "b" + b + "b'" + c + "f+`", s);
            s += "'" + c + "fm" + b + "b" + DIGITS[m] + "b";
            if (zero) {
                s += "1>";
            }
            return s;
        }

        public Array rle11(final int f) {
            final int[] b = new int[n];
            int m = 0;
            int x = -1;
            int k = 0;
            for (int i = 0; i <= n; ++i) {
                final int t = i == n ? -2 : a[i];
                if (t == x && m < 11 * f) {
                    m++;
                }
                else {
                    if (m >= f && m > 3) {
                        b[k++] = 10;
                        b[k++] = m / f - 1;
                        b[k++] = x;
                        for (int j = 0; j < m % f; ++j) {
                            b[k++] = x;
                        }
                    }
                    else {
                        for (int j = 0; j < m; ++j) {
                            b[k++] = x;
                        }
                    }
                    m = 1;
                    x = t;
                }
            }
            return new Array(Arrays.copyOf(b, k));
        }
    }

    private static void score() {
        double p = 1;
        for (int i = 1; i < 6; ++i) {
            final File f = new File("image" + i + ".txt");
            final Img img = Img.read(f);
            final int n = (int) f.length();
            for (int j = 5; j < 10; ++j) {
                final double q = j / 10.0;
                final String s = img.compress(q);
                System.out.println(f.getName() + ", " + q + ": " + n + " -> " + s.length());
                img.verify(s, q);
                p *= s.length();
            }
        }
        System.out.println(Math.pow(p, 1 / 25.0));
    }

    public static void main(final String... args) {
        if (args.length != 2) {
            score();
            return;
        }
        final String fname = args[0];
        final double quality = Double.parseDouble(args[1]);
        try {
            final Img img = Img.read(new File(fname));
            final String s = img.compress(quality);
            img.verify(s, quality);
            final FileWriter fw = new FileWriter(fname + ".cjam");
            fw.write(s);
            fw.close();
        }
        catch (IOException e) {
            throw new RuntimeException();
        }
    }
}

```

Requires the CJam jar in the classpath. If you give it 2 command line arguments (file name and quality), it appends ".cjam" to the file name and writes the compressed image there. Otherwise it calculates its score on the 5 test images, which are assumed to be in the current directory. The program also verifies every compressed image automatically. You may want to double-check the score calculation in case there's any discrepancy.

The techniques used (so far) are: scaling to half (horizontally, vertically or both) if it doesn't reduce the quality too much, a custom-coded RLE, and base conversion to pack more data into each character while remaining in the printable ASCII range.
> 4 votes

# Answer
# Python 3.5 (main and output) (currently noncompeting)

Happy Birthday, Challenge! Here's your present: an answer!

EDIT: Converted output to python code, improved compression rate (slightly) EDIT2: Made it print raw when `size` is 1. Improved score, but score needs to be calculated again. EDIT3: @Dennis pointed out that I still haev bugs to fix, so I marked the answer as noncompeting

Code:

```
import sys
LIST = [' ','`','.',',',':',';',"'",'+','#','@']

def charxel_to_brightness(charxel):
    return LIST.index(charxel)

def brightness_to_charxel(bright):
    return LIST[bright]

def image_to_brightness(imagetext):
    return [list(map(charxel_to_brightness,line)) for line in imagetext.split("\n")]

def brightness_to_image(brightarray):
    return '\n'.join([''.join(map(brightness_to_charxel,line)) for line in brightarray])

def split_into_parts(lst,size):
    return [lst[x:x+size] for x in range(0, len(lst), size)]

def gen_updown(startxel,endxel,size):
    return [[int((size-r)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_leftright(startxel,endxel,size):
    return [[int((size-c)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_tlbr(startxel,endxel,size):
    return [[int((2*size-r-c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_bltr(startxel,endxel,size):
    return [[int((size-r+c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_block(code,startxel,endxel,size):
    if code==0:return gen_updown(startxel,endxel,size)
    if code==1:return gen_leftright(startxel,endxel,size)
    if code==2:return gen_bltr(startxel,endxel,size)
    if code==3:return gen_tlbr(startxel,endxel,size)

def vars_to_data(code,startxel,endxel):
    acc=endxel
    acc+=startxel<<4
    acc+=code<<8
    return acc

def data_to_vars(data):
    code=data>>8
    startxel=(data>>4)&15
    endxel=data&15
    return code,startxel,endxel

def split_into_squares(imgarray,size):
    rows = split_into_parts(imgarray,size)
    allsquares = []
    for rowblock in rows:
        splitrows = []
        for row in rowblock:
            row = split_into_parts(row,size)
            splitrows.append(row)
        rowdict = []
        for row in splitrows:
            for x in range(len(row)):
                if len(rowdict)<=x:
                    rowdict.append([])
                rowdict[x].append(row[x])
        allsquares.append(rowdict)
    return allsquares

def calc_quality(imgarray,comparray):
    acc=0
    for row in range(len(imgarray)):
        for col in range(len(imgarray[row])):
            acc+=pow(imgarray[row][col]-comparray[row][col],2)
    return (1-(acc/81.0/sum([len(row) for row in imgarray]))**.5)**8

def fuse_squares(squarray):
    output=[]
    counter=0
    scounter=0
    sqrow=0
    while sqrow<len(squarray):
        if scounter<len(squarray[sqrow][0]):
            output.append([])
            for square in squarray[sqrow]:
                output[counter].extend(square[scounter])
            scounter+=1
            counter+=1
        else:
            scounter=0
            sqrow+=1
    return output

def main_calc(imgarray,threshold):
    imgarray = image_to_brightness(imgarray)
    size = 9
    quality = 0
    compimg=[]
    datarray=[]
    testdata = [vars_to_data(c,s,e) for c in range(4) for s in range(10) for e in range(10)]
    while quality<threshold:
        squares = split_into_squares(imgarray,size)
        compimg = []
        datarray = []
        testblock = [gen_block(c,s,e,size) for c in range(4) for s in range(10) for e in range(10)]
        for row in squares:
            comprow = []
            datrow=[]
            for square in row:
                quality_values = [calc_quality(square,block) for block in testblock]
                best_quality = quality_values.index(max(quality_values))
                comprow.append(testblock[best_quality])
                datrow.append(testdata[best_quality])
            compimg.append(comprow)
            datarray.append(datrow)
        compimg = fuse_squares(compimg)
        quality = calc_quality(imgarray,compimg)
        print("Size:{} Quality:{}".format(size,quality))
        size-=1
    return brightness_to_image(compimg),datarray,size+1

template = '''def s(d,s,e,z):
 x=range(z)
 return d<1 and[[int((z-r)*(e-s)/z+s)for c in x]for r in x]or d==1 and[[int((z-c)*(e-s)/z+s)for c in x]for r in x]or d==2 and[[int((2*z-r-c)/2*(e-s)/z+s)for c in x]for r in x]or d>2 and[[int((z-r+c)/2*(e-s)/z+s)for c in x] for r in x]
i=lambda a:'\\n'.join([''.join(map(lambda r:" `.,:;'+#@"[r],l))for l in a])
def f(a):
 o=[];c=0;s=0;r=0
 while r<len(a):
  if s<len(a[r][0]):
   o.append([])
   for q in a[r]:
    o[c].extend(q[s])
   s+=1;c+=1
  else:
   s=0;r+=1
 return o
t={};z={}
print(i(f([[s(D>>8,(D>>4)&15,D&15,z)for D in R]for R in t])))'''

template_size_1 = '''print("""{}""")'''

def main(filename,threshold):
    print(filename+" "+str(threshold))
    file = open(filename,'r')
    compimg,datarray,size = main_calc(file.read(),threshold)
    file.close()
    textoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".txt",'w')
    textoutput.write(compimg)
    textoutput.close()
    compoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".py",'w')
    datarray = str(datarray).replace(" ","")
    code = ""
    if size==1:
        code = template_size_1.format(compimg)
    else:
        code= template.format(datarray,str(size))
    compoutput.write(code)
    compoutput.close()
    print("done")

if __name__ == "__main__":
    main(sys.argv[1],float(sys.argv[2]))

```

This answer could use **a lot** of improvements, so I'll probably be working on it more over the weekend.

### How this works:

* Divide image into blocks of size `size`.
* Find best matching block
    + Blocks can have gradient now!
* Calculate quality (according to formula) for entire image.
* If correct, write zipped image to file.
* Otherwise, decrement `size` and try again.

This algorithm works well for low quality (0.5, 0.6) but doesn't work too well on the higher quality images (actually inflates). It is also really slow.

Here I have all the generated files, so you won't have to re-generate them again.
> 2 votes

---
Tags: code-challenge, ascii-art, compression
---


title: Character Counting System

text:
# Question
Title: Character Counting System
**GOAL :** To Implement a character counting program

This is how this counting system works :

input of the program is a set of *printable* ASCII characters . the program counts each type of character , and outputs the number of each character , starting from first mentioned character to last mentioned character .

Example :

```
input : aaaabbbbbcccc    123445b
output : 4 6 4 4 1 1 1 2 1

```

Which `4` is number of `a`s , `6` is number of `b`s , `4` is number of `c`s , `4` is number of spaces () and so on . Also you can split answers with space (like example) , EOL , or anything other than numerals .

**Rules**

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet

It's optional to mention the ungolfed version of program and/or a short explanation .

**Test input :** `ThIs Is ThE iNPUT , WITH 72/2 CHARS!`

**Test output :** `4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1`

# Answer
# MATL, 3 bytes

```
8#u

```

Input is a string enclosed with quotation marks (which is allowed by default)

**Try it online!**

### Explanation

`u` is the `unique` function, which essentially removes duplicates. It can produce up to four outputs. The fourth output is the count of unique characters, identified in order of appearance.

`8#` specifies that the fourth output of `u` should be produced. In general, `2#` means "produce two outputs", `3#` means "produce three outputs" etc. When the maximum number of function outputs is reached, larger numbers mean "take the *first* output only", or "the *second* only" etc. Thus, since `u` has four possible outputs, `4#` would produce all four outputs; `5#` produces the first, `6#` the second, etc.
> 7 votes

# Answer
## 05AB1E, 6 bytes

```
Ùv¹y¢,

```

**Explained**

```
Ùv      # for each unique char in original order
  ¹y¢   # count number of occurances in input string
     ,  # print on newline

```

Try it online
> 4 votes

# Answer
# Pyth, 4 bytes

```
/LQ{

```

Test suite.

### Explanation

```
/LQ{    Input: Q
/LQ{Q   Implicitly fill arguments

   {Q   Yield the unique elements of Q.
 L      For each unique element:
/       Yield its number of occurrences
  Q     in Q.

```
> 4 votes

# Answer
# J, ~~18~~ 15 bytes

```
echo#/.~stdin''

```

Following the challenge spec to write a program, the above is a one-line script in J that reads a line from stdin, computes the result, and prints it to stdout.

If using an online interpreter, it would require **4 bytes** since without stdio, only function arguments could be used.

```
#/.~

```

Straight-forward application of adverbs `/.` and `~` to the tally `#` verb.

## Usage

As a script,

```
$ echo -n 'aaaabbbbbcccc    123445b' | jconsole golf.j
4 6 4 4 1 1 1 2 1

```

As a function,

```
   (#/.~) 'aaaabbbbbcccc    123445b'
4 6 4 4 1 1 1 2 1

```

## Explanation

```
#/.~  Input: s
   ~  Reflects the input
 /.   An adverb that executes a verb on each set of identical items in s
      Operates in the order of first-seen distinct items in s
#     Get the size of each set of identical items
      Returns a list of the sizes of identical items

```
> 3 votes

# Answer
## CJam, 9 bytes

```
l__&\fe=p

```

Test it here.

### Explanation

```
l    e# Read input.
__   e# Make two copies.
&    e# Set intersection - removes duplicates.
\    e# Swap with input.
fe=  e# For each (unique) character, count its occurrences.
p    e# Print as array literal.

```
> 2 votes

# Answer
# Dyalog APL, 10 bytes

# Shortest by byte count

```
+⌿t∘.=∪t←⍞

```

`t←⍞` get character input and store as *t*

\`∪' unique elements of

`t∘.=` table of which elements of t are equal to (the unique elements of t)

`+⌿` sum the columns

### 5 character solution which unfortunately is 15 bytes:

```
⊢∘≢⌸⍞

```

get character input

make a table of contents containing...

`⊢∘≢` the tally () of the indices while the entries are ignored ()
> 2 votes

# Answer
## Jelly, 4 bytes

```
Qċ@€

```

Try it online

## Explanation

```
Qċ@€   Main link. Argument: S

Q      Remove duplicate characters from S.
       Current value v contains each character of S once sorted by first appearance.
  @€   For each character in v.
 ċ       count its occurrence in S.

```
> 2 votes

# Answer
## Mathematica, 56 bytes

```
Print@StringRiffle[Last/@Tally@Characters@InputString[]]

```

Essentially, `Tally` does exactly what the challenge asks for (although it gives pairs of `{element, count}`). The rest is just for working with strings and proper I/O for a full program.
> 1 votes

# Answer
# Retina, ~~30~~ 28 bytes

2 bytes thanks to Martin Ender.

```
+`((.).+)\2
$2$1
(.)\1*
$.&¶

```

Try it online!
> 1 votes

# Answer
# Brachylog, 32 bytes

```
:efd:?:{tL,?he:L:{t:.m~h?}fl.}f.

```

Awfully long but there's no simple way of counting elements of something yet…
> 1 votes

# Answer
# Java 7, ~~246~~ ~~235~~ ~~231~~ 213 bytes

Loads of bytes removed thanks to *cliffroot*.

```
import java.util.*;class M{public static void main(String[]a){Map<Long,Long>m=new LinkedHashMap();for(long c:a[0].toCharArray())m.put(c,m.get(c)!=null?m.get(c)+1:1);for(Long e:m.values())System.out.print(e+" ");}}

```

**Ungolfed & test code:**

Try it here.

```
import java.util.*;

class Main{
  public static void main(String[] a){
    // Test code:
    a = new String[]{ "ThIs Is ThE iNPUT , WITH 72/2 CHARS!" };

    Map<Long, Long> m = new LinkedHashMap();
    for(long c : a[0].toCharArray()){
      m.put(c, m.get(c) != null ? m.get(c) + 1 : 1);
    }
    for(Long e : m.values()){
      System.out.print(e + " ");
    }
  }
}

```

**Output:**

```
4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1

```
> 1 votes

# Answer
# Python 3, ~~134~~ 81 bytes

```
s,r=input(),[]
for c in s:
 k,s=s.count(c),s.replace(c,'')
 if k:r+=[k]
print(*r)

```

**Output:**

```
4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1

```

Not that short :(

---

**Another approach: 109 bytes**

Not shorter than the others but the counting happens in a one-liner.

```
s=input()
k=[i[1]for i in sorted({i:str(s.count(i))for i in s}.items(),key=lambda v:s.index(v[0]))]
print(*k)

```

---

**Edit:** Golfed 53 bytes thanks to @Dr Green Eggs and Iron Man **Edit 2:** Added one-liner method
> 1 votes

# Answer
# Java 7, ~~172~~ 168 bytes

```
class M{public static void main(String[]a){int[]m=new int[256];byte[]b=a[0].getBytes();for(int z:b)m[z]++;for(int z:b){System.out.print(m[z]>0?(m[z]+" "):"");m[z]=0;}}}

```

Stores number of occurrences in an int array, then for each char print number of occurrences and replace this value with zero so it won't be printed again.

Whitespaces and comments added:

```
class M{
    public static void main(String[]a){
        int[]m=new int[256]; // map, ascii value to number of occurrences
        byte[b]=a[0].getBytes();
        for(int z:b)m[z]++; // count number of occurrences
        for(int z:b){
            System.out.print(m[z]>0?(m[z]+" "):""); // print result
            m[z]=0; // make it not be printed again
        }
    }
}

```

See it online: https://ideone.com/7X58F9
> 1 votes

# Answer
**C#**

```
public static void Main(string[] args)
    {
        string str = "aaaabbbbbcccc    123445b";
        Dictionary<char, int> counts = new Dictionary<char, int>();

        for (int i = 0; i < str.Length; i++)
           if (counts.ContainsKey(str[i]))
               counts[str[i]]++;
           else
              counts.Add(str[i], 1);

        foreach (var count in counts)
         Console.WriteLine("{0} = {1}", count.Key, count.Value.ToString());
    }

```
> 0 votes

# Answer
# ES6, 90 bytes

```
a=prompt();b=new Map();for(c of a)b.set(c,(b.get(c)|0)+1);alert([...b.values()].join(' '))
```
> 0 votes

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

3 bytes shorter:

```
s,a=input(),[]
for y in s:a+=(y,'')[y in a]
print([s.count(x)for x in a])

```

Old version:

```
s=input();print([s.count(x)for x in sorted(set(s),key=lambda i:s.index(i))])

```

Iterates over a sorted set of unique characters from the input, counts the occurrences, and outputs a list of the counts.
> 0 votes

# Answer
**Python 2.7 - 103 Bytes (Ungolfed)**

```
i=list(raw_input())
print ''.join([str(e) for e in map(lambda x,y:x!=y and i.count(x)or' ',i,['']+i) ])

```

**edit:** Thanks to Dr Green Eggs and Iron Man for helping to reduce 47 Bytes!
> 0 votes

# Answer
## Python 3, 93 bytes

```
s=input();c,o=[],""
for i in s:
 if i not in c:c+=i
for i in c:o+=str(s.count(i))+" "
print o

```
> 0 votes

# Answer
## Matlab, 47 chars

```
@(y)arrayfun(@(x)sum(y==x),unique(y,'stable'))

```

Reasonably straightforward, though the default behavior of Matlab's `unique` function to sort the values makes the function rather longer.
> 0 votes

# Answer
## Pyke, 3 bytes

```
}F/

```

Try it here!

```
for i in uniquify(input): print input.count(i)

```
> 0 votes

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


title: The handshake problem

text:
# Question
Title: The handshake problem
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs. This should mean that you should expect `n >= 0`

Test cases

```
(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116

```

Normal golfing rules apply and shortest code wins. If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

# Answer
> 5 votes
## Jelly, 2 bytes

```
c2

```

Try it online!

# Answer
> 9 votes
# JavaScript ES6, 16

```
n=>n%1?0:~-n*n/2

```

*Test*

```
f=n=>n%1?0:~-n*n/2

function test()
{
  var i=I.value
  O.textContent=f(i)
}
```

```
<input id=I oninput=test()><span id=O></span>
```

# Answer
> 8 votes
# 05AB1E, 2 bytes

Code:

```
2c

```

Try it online!.

# Answer
> 6 votes
# MATL, 3 bytes

```
2Xn

```

**Try it online!**

The code computes the binomial coefficient "*n* choose 2", where *n* is the input. For non-integer input no output is produced.

```
       % Take input implicitly
2      % Push 2
Xn     % n-choose-k
       % Display implicitly

```

# Answer
> 6 votes
# Brainfuck, ~~22~~ 21 bytes

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

```

Try it online! Note, that brainfuck takes input and output through ASCII, so to enter a "49", you enter ascii value 49, e.g. `1`. Brainfuck has no concept of non-integers, so it is impossible to enter one.

# Answer
> 5 votes
## Matlab, 61 23 bytes

```
@(x)~mod(x,1)*x*(x-1)/2

```

Improvements courtesy Luis Mendo.

*Old answer:*

`@(x)eval('if isnumeric(x) disp((mod(x,1)==0)*x*(x-1)/2);end')`

An anonymous function that calls `eval`. Matlab considers all numbers entered to be doubles unless you explicitly tell it otherwise, so testing for integerness via built-in isn't really an option unless you want to condition your input heavily-- thus the isnumeric and the mod1.

As well, Matlab doesn't allow conditional statements in anonymous functions, so you have to kludge around that by way of an `eval` statement that evaluates a string. So fun.

The "falsey" output is that it doesn't print anything at all for nonnumerics and prints `0` for a non-integer numeric. For a valid input, it will print the result.

# Answer
> 4 votes
**Python, 37 50, 46, 32, 26 bytes**

```
lambda a:a%1==0and a*~-a/2

```

Making use of the fact that the solution of the handshake problem is (N-1) + (N-2) ... 2 + 1 for N people. The most problematic is the falsey value when a non-int is given.

Big thanks to Leaky Nun and Martin Ender!

# Answer
> 3 votes
# CJam, 7 bytes

```
ri_(*2/

```

Computes *n*\*(*n*−1), where *n* is the input. For non-integer input it produces no output.

**Try it online!**

```
r     e# Read input
i     e# Convert to integer
_     e# Duplicate
(     e# Subtract 1
*     e# Multiply
2/    e# Divide by 2.
      e# Implicit display

```

# Answer
> 3 votes
## Mathematica, 19 bytes

```
#(#-1)/2/._Real->0&

```

This first computes the result using the explicit formula `n(n-1)/2` but then replaces it with `0` if the that gives a floating-point result.

Just for fun, some alternatives to computing the result (minus the input validation) are:

```
#~Binomial~2
Tr@Range@#-#
n~Sum~{n,#-1}
PolygonalNumber@#-#

```

# Answer
> 3 votes
## R, 28 bytes

Returns `0` if the input, `x`, is not an integer

```
x=scan();(x%%1==0)*x*(x-1)/2

```

# Answer
> 3 votes
## ArnoldC, 266 bytes

ArnoldC has no concept of non-integers, so it is impossible to enter one.

```
LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 0
GET TO THE CHOPPER r
HERE IS MY INVITATION n
GET DOWN 1
YOU'RE FIRED n
HE HAD TO SPLIT 2
ENOUGH TALK
I'LL BE BACK r
HASTA LA VISTA, BABY

```

Explanations:

```
DeclareMethod f
        MethodArguments n
        NonVoidMethod
        DeclareInt r
        SetInitialValue 0
            AssignVariable r
                   SetValue n
                   MinusOperator 1
                   MultiplicationOperator n
                   DivisionOperator 2
            EndAssignVariable
        Return r
EndMethodDeclaration

```

# Answer
> 2 votes
# Pyth, 7 bytes

```
~~?sIQ.cQ2Z~~
.x.cQ2Z

```

Test suite.

# Answer
> 2 votes
## CJam, 5 bytes

```
ri,1b

```

Prints nothing (except to STDERR) for non-integer input.

Try it online!

### Explanation

```
ri  e# Read input and try to convert to integer N.
,   e# Turn into range [0 1 2 ... n-1].
1b  e# Sum the list by treating it as base-1 digits. We do this instead of
    e# a simple reduction (:+) because the latter fails for empty lists.

```

# Answer
> 2 votes
# Desmos, 11 bytes

```
.5nn-.5n
n=1

```

Try it here

Ungolfed formula:

# Answer
> 2 votes
## Hoon, 30 bytes

```
|=
n/@
(div (mul n (dec n)) 2)

```

Just compute `(n * (n-1))/2`. Hoon is strongly typed, so you *can't* call this function with a float or negative number.

# Answer
> 2 votes
# Python 3, 22 bytes

```
lambda z:sum(range(z))

```

Makes use of Python's standard library. Raises an error whenever the function is fed with a non-integer.

# Answer
> 2 votes
## Python 3, 32 16 bytes

```
lambda n:n*~-n/2

```

Throws an error if n is not an integer.

Old Version:

```
lambda n:(0,n*~-n/2)[n==int(n)]

```

# Answer
> 1 votes
## PowerShell v2+, 33 bytes

```
param($n)$n*($n-1)/2*($n-is[int])

```

Full program. 20 bytes to compute `n(n-1)/2` and 13 bytes to validate input. Uses the `-is` operator, so requires V2 or newer.

# Answer
> 1 votes
# J, ~~14~~ 8 bytes

```
2&!*]=<.

```

6 bytes saved thanks to miles!

Explaination:

```
2&!      NB. Binomial coefficient of 2 and the argument
   *     NB. Times...
    ]=<. NB. argument == floor(argument)

```

Previous solution: `-:@(*<:)*(=<.)`

# Answer
> 1 votes
# Dyalog APL, 9 bytes

```
2∘!×(|=⌊)

```

The chose-2 times (whether the abs equals the floor).

# Answer
> 1 votes
# dc, 18 bytes

```
[d/]sqdX0!=qd1-*2/

```

### Explanation

```
[d/]sq

```

Store in register `q` a macro that replaces top of stack with 1 (by dividing by itself).

```
dX0!=q

```

If there are any fraction digits, then execute the macro.

```
d1-*2/

```

Compute ½n(n-1). If we started with 1 (either as input or because a non-integer value was entered) the result will be 0.

# Answer
> 1 votes
# Factor with `load-all`, 12 bytes

```
[ iota sum ]

```

Same as this answer.

# Answer
> 1 votes
# Java, 363 bytes

I thought I ought to make sure everybody gets a chance to meet everybody else.

Unfortunately some of the party guests do have to ask if they've met someone before, to avoid shaking someone's hand twice. Hopefully the guests are pretty good at recognizing faces.

Golfed:

```
import java.util.ArrayList;public class H{static int h = 0;public static void main(String[] a){int b = Integer.parseInt(a[0]);P[] e = new P[b];for(int i=0;i<b;i++){e[i] = new P();}for(P p : e){for(P o : e){p.s(o);}}System.out.print(h);}}class P {ArrayList<P> l = new ArrayList<P>();void s(P o){if(o.equals(this)){return;}if(!o.l.contains(this)){H.h++;l.add(o);}}}

```

Un-golfed:

```
import java.util.ArrayList;

public class PartyHost {
    static int shakes = 0;
    public static void main(String[] args){
        int amount = Integer.parseInt(args[0]);
        Person[] people = new Person[amount];
        for(int i=0; i<amount;i++){
            people[i] = new Person();
            // welcome to the party!
        }
        // well, we gotta get this party rockin'. hey, have you met my friend...
        for(Person p : people){
            for(Person other : people){
                p.handshake(other);
            }
        }
        System.out.print(shakes);
    }
}

class Person {
    ArrayList<Person> already_shook = new ArrayList<Person>();
    void handshake(Person other){
        // hmm, have we met already?
        if(other.equals(this)){
            // I mean, I guess I could shake hands with myself... maybe later.
            return;
        }
        if(!other.already_shook.contains(this)){
            // it seems not!
            // *firm grasp. maintain eye contact*
            // uh oh don't hold on too long
            // hope he doesn't grab too early or too late
            PartyHost.shakes++;
            already_shook.add(other);
        }
    }
}

```

# Answer
> 0 votes
# Perl 5, 25 bytes

A subroutine:

```
{($_=pop)*!/\D/*($_-1)/2}

```

See it in action:

```
perl -e'print sub{($_=pop)*!/\D/*($_-1)/2}->(3.14)'

```

# Answer
> 0 votes
# , 5 chars / 7 bytes

```
МƦ⁽ï2

```

`Try it here (ES6 browsers only).`

Builtins are pretty cool.

# Answer
> 0 votes
# RETURN, 8 bytes

```
[$1-×2÷]

```

`Try it here.`

Anonymous lambda that leaves result as top of stack. Usage:

```
10[$1-×2÷]!

```

# Explanation

```
[      ]  lambda
 $1-      n-1
    ×     *n
     2÷   /2

```

# Answer
> 0 votes
# Google Sheets, ~~17~~ 14 bytes

```
=((B1^2)-B1)/2

```

Cell B1 is the input.

# Answer
> 0 votes
## Haskell, 15 bytes

```
f x=sum[1..x-1]

```

`[x..y]` ranges are inclusive...

Oh and I don't know how to handle the non-integers...

# Answer
> 0 votes
## Golisp, 18 bytes

```
{(n)~[+range[1n]]}

```

Python equivalent: `lambda n: sum(range(1, n))`.

Oh and Golisp don't have floating point number (for now)

---
Tags: code-golf, math, arithmetic, combinatorics
---


title: Generate ASCII Art

text:
# Question
Title: Generate ASCII Art
Given a black-and-white image in any reasonable lossless format as input, output ASCII art that is as close to the input image as possible.

## Rules

* Only linefeeds and ASCII bytes 32-127 may be used.
* The input image will be cropped so that there is no extraneous whitespace surrounding the image.
* Submissions must be able to complete the entire scoring corpus in under 5 minutes.
* Only raw text is acceptable; no rich text formats.
* The font used in the scoring is 20-pt Linux Libertine.
* The output text file, when converted to an image as described below, must be the same dimensions as the input image, within 30 pixels in either dimension.

## Scoring

These images will be used for scoring:

You can download a zipfile of the images here.

Submissions should not be optimized for this corpus; rather, they should work for any 8 black-and-white images of similar dimensions. I reserve the right to change the images in the corpus if I suspect submissions are being optimized for these specific images.

The scoring will be performed via this script:

```
#!/usr/bin/env python
from __future__ import print_function
from __future__ import division
# modified from http://stackoverflow.com/a/29775654/2508324
# requires Linux Libertine fonts - get them at https://sourceforge.net/projects/linuxlibertine/files/linuxlibertine/5.3.0/
# requires dssim - get it at https://github.com/pornel/dssim
import PIL
import PIL.Image
import PIL.ImageFont
import PIL.ImageOps
import PIL.ImageDraw
import pathlib
import os
import subprocess
import sys

PIXEL_ON = 0  # PIL color to use for "on"
PIXEL_OFF = 255  # PIL color to use for "off"

def dssim_score(src_path, image_path):
    out = subprocess.check_output(['dssim', src_path, image_path])
    return float(out.split()[0])

def text_image(text_path):
    """Convert text file to a grayscale image with black characters on a white background.

    arguments:
    text_path - the content of this file will be converted to an image
    """
    grayscale = 'L'
    # parse the file into lines
    with open(str(text_path)) as text_file:  # can throw FileNotFoundError
        lines = tuple(l.rstrip() for l in text_file.readlines())

    # choose a font (you can see more detail in my library on github)
    large_font = 20  # get better resolution with larger size
    if os.name == 'posix':
        font_path = '/usr/share/fonts/linux-libertine/LinLibertineO.otf'
    else:
        font_path = 'LinLibertine_DRah.ttf'
    try:
        font = PIL.ImageFont.truetype(font_path, size=large_font)
    except IOError:
        print('Could not use Libertine font, exiting...')
        exit()

    # make the background image based on the combination of font and lines
    pt2px = lambda pt: int(round(pt * 96.0 / 72))  # convert points to pixels
    max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
    # max height is adjusted down because it's too large visually for spacing
    test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    max_height = pt2px(font.getsize(test_string)[1])
    max_width = pt2px(font.getsize(max_width_line)[0])
    height = max_height * len(lines)  # perfect or a little oversized
    width = int(round(max_width + 40))  # a little oversized
    image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF)
    draw = PIL.ImageDraw.Draw(image)

    # draw each line of text
    vertical_position = 5
    horizontal_position = 5
    line_spacing = int(round(max_height * 0.8))  # reduced spacing seems better
    for line in lines:
        draw.text((horizontal_position, vertical_position),
                  line, fill=PIXEL_ON, font=font)
        vertical_position += line_spacing
    # crop the text
    c_box = PIL.ImageOps.invert(image).getbbox()
    image = image.crop(c_box)
    return image

if __name__ == '__main__':
    compare_dir = pathlib.PurePath(sys.argv[1])
    corpus_dir = pathlib.PurePath(sys.argv[2])
    images = []
    scores = []
    for txtfile in os.listdir(str(compare_dir)):
        fname = pathlib.PurePath(sys.argv[1]).joinpath(txtfile)
        if fname.suffix != '.txt':
            continue
        imgpath = fname.with_suffix('.png')
        corpname = corpus_dir.joinpath(imgpath.name)
        img = text_image(str(fname))
        corpimg = PIL.Image.open(str(corpname))
        img = img.resize(corpimg.size, PIL.Image.LANCZOS)
        corpimg.close()
        img.save(str(imgpath), 'png')
        img.close()
        images.append(str(imgpath))
        score = dssim_score(str(corpname), str(imgpath))
        print('{}: {}'.format(corpname, score))
        scores.append(score)
    print('Score: {}'.format(sum(scores)/len(scores)))

```

The scoring process:

1. Run the submission for each corpus image, outputting the results to `.txt` files with the same stem as the corpus file (done manually).
2. Convert each text file to a PNG image, using 20-point font, cropping out whitespace.
3. Resize the result image to the dimensions of the original image using Lanczos resampling.
4. Compare each text image with the original image using `dssim`.
5. Output the dssim score for each text file.
6. Output the average score.

Structural Similarity (the metric by which `dssim` calculates scores) is a metric based on human vision and object identification in images. To put it plainly: if two images look similar to humans, they will (probably) have a low score from `dssim`.

The winning submission will be the submission with the lowest average score.

related

# Answer
## Java, score 0.57058675

This is actually my first time doing image manipulation so it's kind of awkward but I think it turned out OK.

I couldn't get dssim to work on my machine, but I was able to make images using PIL.

Interestingly, the font tells me in Java that each of the characters I'm using are width `6`. You can see that in my program `FontMetrics::charWidth` is `6` for all characters that I have used. The `{}` logo looks pretty decent in a monospace font. But for some reason the lines do not actually line up in the full text file. I blame ligatures. (And yes, I *should* be using the correct font.)

In monospaced font:

```
                                                                                .
                         .,:ff:,                                                   ,:fff::,.
                ,ff .fIIIIIf,                                                         .:fIIIIIf.:f:.
            .,:III: ,ff::                       ..,,            ,,..                      ,:fff, IIII.,
          :IIf,f:,:fff:,                  .:fIIIIIII.          .IIIIIIIf:.                 .,:fff:,ff IIf,
       ,.fIIIf,:ffff,                   ,IIIIIII:,,.            .,,:IIIIIII.                  .:ffff:,IIII,:.
     ,III.::.,,,,,.                     IIIIII:                      ,IIIIII                     ,,,,,.,:,:IIf
     IIIII :ffIIf,                      IIIIII,                      .IIIIII                      :IIIf:,.IIIIf.
  ,II,fIf.:::,..                        IIIIII,                      .IIIIII                       ..,:::,,If::II
  IIIIf.  ,:fII:                       .IIIIII,                      .IIIIII.                       IIff:.  :IIII:
 ::IIIIf:IIIf: .                  ,::fIIIIIII,                        ,fIIIIIIf::,                   ,ffIII,IIIIf,,
:IIf:::    .,fI:                  IIIIIIIII:                            :IIIIIIIIf                  If:,    .::fIIf
 IIIIII, :IIIIf                     .,:IIIIIIf                        fIIIIII:,.                    ,IIIII. fIIIII:
 ,:IIIII ff:,   f,                      IIIIII,                      .IIIIII                      f.  .::f::IIIIf,.
 fIf::,,     ,fIII                      IIIIII,                      .IIIIII                     :III:      ,,:fII.
  fIIIIIIf, :IIIIf   ,                  IIIIII,                      .IIIIII                 .,  ,IIIII. :fIIIIII,
   .:IIIIIII,ff,    :II:                IIIIIIf                      fIIIIII               .fII.   .:ff:IIIIIIf,
     :fffff:,      IIIIIf   ,            :IIIIIIIfff            fffIIIIIII:           ..   IIIII:      ::fffff,
      .fIIIIIIIf:, fIIII,   ,IIf,           ,:ffIIII.          .IIIIff:,          .:fII    fIIII,.:ffIIIIIII:
         ,fIIIIIIIIIf:,     ,IIIII:  .,::,                               .,::,  .IIIIII      ::fIIIIIIIIf:.
             :fffffff,      .fIIIII,   .IIIIIf:                     ,:fIIII:    IIIIII:       :fffffff,
              .:fIIIIIIIIIIIIffffI:      IIIIIIII.                :IIIIIII:     .fIffffIIIIIIIIIIII:,
                   ,:fIIIIIIIIIIIf,       .:fIIIII               ,IIIIIf,        :IIIIIIIIIIIff,.
                         .:ffffffffIIIIIIIIIIIfff:.              ,ffffIIIIIIIIIIIfffffff:,
                             .,:ffIIIIIIIIIIIIIIIIf,   .,,,,.  .:fIIIIIIIIIIIIIIIIff:,.
                                       ....... .,,:fffff:.,:fffff:,.  .......
                                    ..,,:fffIIIIf:,.            .,:fIIIIff::,,..
                                   .IIIIIf:,.                          .,:fIIIII
                                     f,                                      ,f

```

After running it through the image tool:

Anyway, here's the actual code.

```
//package cad97;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;

public final class AsciiArt {

    private static final Font LINUX_LIBERTINE = new Font("LinLibertine_DRah", Font.PLAIN, 20);
    private static final FontMetrics LL_METRICS = Toolkit.getDefaultToolkit().getFontMetrics(LINUX_LIBERTINE);
    // Toolkit::getFontMetrics is deprecated, but that's the only way to get FontMetrics without an explicit Graphics environment.
    // If there's a better way to get the widths of characters, please tell me.

    public static void main(String[] args) throws IOException {
        File jar = new java.io.File(AsciiArt.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        if (args.length != 1) {
            String jarName = jar.getName();
            System.out.println("Usage: java -jar " + jarName + " file");
        } else {
            File image = new File(args[0]);
            try (InputStream input = new FileInputStream(image)) {
                String art = createAsciiArt(ImageIO.read(input), LINUX_LIBERTINE, LL_METRICS);
                System.out.print(art); // If you want to save as a file, change this.
            } catch (FileNotFoundException fnfe) {
                System.out.println("Unable to find file " + image + ".");
                System.out.println("Please note that you need to pass the full file path.");
            }
        }
    }

    private static String createAsciiArt(BufferedImage image, Font font, FontMetrics metrics) {
        final int height = metrics.getHeight();
        final Map<Character,Integer> width = new HashMap<>();
        for (char c=32; c<127; c++) { width.put(c, metrics.charWidth(c)); }

        StringBuilder art = new StringBuilder();

        for (int i=0; i<=image.getHeight(); i+=height) {
            final int tempHeight = Math.min(height, image.getHeight()-i);
            art.append(createAsciiLine(image.getSubimage(0, i, image.getWidth(), tempHeight), width));
        }

        return art.toString();
    }

    private static String createAsciiLine(BufferedImage image, Map<Character,Integer> charWidth) {
        if (image.getWidth()<6) return "\n";
        /*
        I'm passing in the charWidth Map because I could use it, and probably a later revision if I
        come back to this will actually use non-6-pixel-wide characters. As is, I'm only using the
        6-pixel-wide characters for simplicity. They are those in this set: { !,./:;I[\]ft|}
        */
        assert charWidth.get(' ') == 6; assert charWidth.get('!') == 6;
        assert charWidth.get(',') == 6; assert charWidth.get('.') == 6;
        assert charWidth.get('/') == 6; assert charWidth.get(':') == 6;
        assert charWidth.get(';') == 6; assert charWidth.get('I') == 6;
        assert charWidth.get('[') == 6; assert charWidth.get('\\') == 6;
        assert charWidth.get(']') == 6; assert charWidth.get('f') == 6;
        assert charWidth.get('t') == 6; assert charWidth.get('|') == 6;

        // Measure whiteness of 6-pixel-wide sample
        Raster sample = image.getData(new Rectangle(6, image.getHeight()));
        int whiteCount = 0;
        for (int x=sample.getMinX(); x<sample.getMinX()+sample.getWidth(); x++) {
            for (int y=sample.getMinY(); y<sample.getMinY()+sample.getHeight(); y++) {
                int pixel = sample.getPixel(x, y, new int[1])[0];
                whiteCount += pixel==1?0:1;
            }
        }

        char next;

        int area = sample.getWidth()*sample.getHeight();

        if (whiteCount > area*0.9) {
            next = ' ';
        } else if (whiteCount > area*0.8) {
            next = '.';
        } else if (whiteCount > area*0.65) {
            next = ',';
        } else if (whiteCount > area*0.5) {
            next = ':';
        } else if (whiteCount > area*0.3) {
            next = 'f';
        } else {
            next = 'I';
        }

        return next + createAsciiLine(image.getSubimage(charWidth.get(','), 0, image.getWidth()-sample.getWidth(), image.getHeight()), charWidth);
    }

}

```

Compile:

* Make sure you have the JDK installed
* Make sure that the JDK bin is on your PATH (for me it's `C:\Program Files\Java\jdk1.8.0_91\bin`)
* Save the file as `AsciiArt.java`
* `javac AsciiArt.java`
* `jar cvfe WhateverNameYouWant.jar AsciiArt AsciiArt.class`

Usage: `java -jar WhateverNameYouWant.jar C:\full\file\path.png`, prints to STDOUT

REQUIRES the source file to be saved with 1-bit depth and the sample for a white pixel to be `1`.

Scoring output:

```
corp/board.png: 0.6384
corp/Doppelspalt.png: 0.605746
corp/down.png: 1.012326
corp/img2.png: 0.528794
corp/pcgm.png: 0.243618
corp/peng.png: 0.440982
corp/phi.png: 0.929552
corp/text2image.png: 0.165276
Score: 0.57058675

```
> 5 votes

---
Tags: code-challenge, ascii-art, image-processing
---


title: Play scrabble with the periodic table

text:
# Question
Title: Play scrabble with the periodic table
You've got a set of tiles with the symbols from the periodic table. Each symbol appears once. You're thinking up words to make but you want to know if it's possible or not.

## The Challenge

Write a program in your favourite language that will take in a string as an input parameter. You may assume that input is not null, has no spaces and consists of ASCII characters.

Your program should take that string and output a truthy value if that word can made up of symbols from the periodic table of elements, and a falsey value if the word cannot.

To make this challenge more difficult, you may not use a symbol twice. So if you use Nitrogen `N` you may not use `N` again in the same word.

## Rules

Standard loopholes are not allowed. You may use symbols from elements 1-118 (Hydrogen to Ununoctium). You can find a list of all the elements here. You may read the list of symbols in from a file or input arguments if you wish.

## Test Cases:

```
Laos - true (LaOs)
Amputation - true (AmPuTaTiON)
Heinous - true (HeINoUS)
Hypothalamus - true (HYPoThAlAmUS)
Singapore - true (SiNGaPoRe)
Brainfuck - true (BRaInFUCK)
Candycane - false

```

This is a code golf challenge, shortest code wins.

**BEFORE YOU CLOSE AS DUPLICATE:** While this may seem similar to this challenge, I feel it is different because it is not 'Generate a list of all words that are possible from the periodic table', it is 'Take in arbitrary input and determine if it can be made from the periodic table'

# Answer
## 05AB1E, 16 bytes

```
œvyŒ€J})˜Ùvy²Q}O

```

**Explained**

```
œv                # for each permutation of the list of elements
  yŒ              # get all sublist of elements
    €J            # join as strings to form the words possible to spell
      })˜Ù        # convert to list of unique spellable strings
          vy²Q}   # compare each word with input word
               O  # sum giving 1 if the word is found, else 0

```

**Warning:** Extremely slow. I recommend testing on a much smaller subset of elements in the online interpreter.

Takes list of elements as first argument.
Takes word to test as second argument.
Returns 1 for true and 0 for false.

Try it online on a small subset of elements
> 3 votes

# Answer
# Brachylog, 7 bytes

```
spc~@l.

```

Call with the list of symbols (all lowercase) as Input, and the word as Output, e.g. `run_from_atom('spc~@l.', ["he":"n":"o":"li"], "Nohe").` .

**Warning:** this is extremely inefficent when all symbols are in the list.

### Explanation

```
spc        Create a string from a permutation of a subset of the Input
   ~@l.    This string can unify with the lowercase version of the Output

```
> 3 votes

# Answer
## JavaScript (Firefox 48 or earlier), 103 bytes

```
f=(w,e=`
H
He
... (list of elements not included in the byte count) ...
Uus
Uuo
`)=>!w||e.match(/\w+/g).some(s=>!w.search(s,`i`)&&f(w.slice(s.length),e.replace(`
${s}
`,`
`)))

```
> 1 votes

# Answer
# Pyth - 13 bytes

Just checks if any partition of lowercased input has all parts in the periodic table.

```
sm.A}RQd./rzZ

```

On mobile, so couldn't set up an actual test suite, but try this.
> 1 votes

# Answer
# Pyth, 11 bytes

```
s}RySQSM./z

```

Try it online. Test suite.

Written on my phone, but should work. **Very slow for a large number of elements or a long string.**

### Explanation

* Take all partitions (`./`) of the input (`z`).
* Sort (`S`) each partition (`M`).
* For each partition (`R`), see if it is in (`}`) the list of all subsets (`y`) of the sorted (`S`) periodic table given as input (`Q`).
* Sum (`s`) the resulting list of booleans.
> 1 votes

---
Tags: code-golf
---


title: Index sum and strip my matrix

text:
# Question
Title: Index sum and strip my matrix
## Index sum and strip my matrix

Given a matrix/2d array in your preferable language

**Input:**

* The matrix will always have an odd length
* The matrix will always be perfectly square
* The matrix values can be any integer in your language (positive or negative)

---

**Example:**

```
1  2  3  4  5  6  7
2  3  4  5  6  7  8
3  4  50 6  7  8  9
4  5  6 100 8  9  10
5  6  7  8 -9  10 11
6  7  8  9  10 11 12
7  8 900 10 11 12 0

```

---

**Definitions:**

* The "central number" is defined as the number that has the same amount of numbers to the left,right,up and down

**In this case its middlemost 100**

* The "outer shell" is the collection of numbers which their x and y index is or 0 or the matrix size

---

```
1  2  3  4  5  6  7
2                 8
3                 9
4                 10
5                 11
6                 12
7  8 900 10 11 12 0

```

## Your task:

Add to the central number the sum of each row and column after multiplying the values in each by their 1-based index

**A single row for example**

```
4  5  6  7  8

```

**for each number**

```
number * index + number * index.....

4*1 + 5*2 + 6*3 + 7*4 + 8*5 => 100

```

---

**example:**

```
 2 -3 -9  4  7  1  5  => 61
-2  0 -2 -7 -7 -7 -4  => -141
 6 -3 -2 -2 -3  2  1  => -10
 8 -8  4  1 -8  2  0  => -20
-5  6  7 -1  8  4  8  => 144
 1  5  7  8  7 -9 -5  => 10
 7  7 -2  2 -7 -8  0  => -60
                         |
78 65 60 45 -15 -89 10   => 154
                     |
                     => -16

```
* For all rows and columns you combine these values..
* Now you sum these too =\> 154-16 = 138
* You add that number to the "central number" and remove the "outer shell" of the matrix

---

```
 0 -2 -7 -7 -7     => -88
-3 -2 -2 -3  2     => -15
-8  4 1+138 -8  2  => 395
 6  7 -1  8  4     => 69
 5  7  8  7 -9     => 26

19 69 442 30 -26

```

do this untill you end up with a single number

```
-2 -2 -3     => -15
 4  1060 -8  => 2100
 7 -1  8     => 29

27 2115 5

```
* Add 2114+2147 to 1060
* Remove the "outer shell" and get 5321
* Now we have a single number left

**this is the output!**

test cases:

```
-6

-6

```

---

```
-7 -1  8
-4 -6  7
-3 -6  6

2

```

---

```
 6  7 -2  5  1
-2  6 -4 -2  3
-1 -4  0 -2 -7
 0  1  4 -4  8
-8 -6 -5  0  2

-365

```

---

```
 8  3  5  6  6 -7  5
 6  2  4 -2 -1  8  3
 2  1 -5  3  8  2 -3
 3 -1  0  7 -6  7 -5
 0 -8 -4 -9 -4  2 -8
 8 -9 -3  5  7  8  5
 8 -1  4  5  1 -4  8

17611

```

---

```
-9 -7  2  1  1 -2  3 -7 -3  6  7  1  0
-7 -8 -9 -2  7 -2  5  4  7 -7  8 -9  8
-4  4 -1  0  1  5 -3  7  1 -2 -9  4  8
 4  8  1 -1  0  7  4  6 -9  3 -9  3 -9
-6 -8 -4 -8 -9  2  1  1 -8  8  2  6 -4
-8 -5  1  1  2 -9  3  7  2  5 -6 -1  2
-8 -5 -7 -4 -9 -2  5  0  2 -4  2  0 -2
-3 -6 -3  2 -9  8  1 -5  5  0 -4 -1 -9
-9 -9 -8  0 -5 -7  1 -2  1 -4 -1  5  7
-6 -9  4 -2  8  7 -9 -5  3 -1  1  8  4
-6  6 -3 -4  3  5  6  8 -2  5 -1 -7 -9
-1  7 -9  4  6  7  6 -8  5  1  0 -3  0
-3 -2  5 -4  0  0  0 -1  7  4 -9 -4  2

-28473770

```

## This is a codegolf challenge so the program with the lowest bytecount wins

# Answer
> 4 votes
# MATL, ~~36~~ 34 bytes

```
tnq?`t&+stn:*sytn2/)+ 7M(6Lt3$)tnq

```

Input is a 2D array with `;` as row separator

Try it online! Or verify all test cases.

### Explanation

```
tnq       % Take input. Duplicate, get number of elements, subtract 1
?         % If greater than 0
  `       %   Do...while
    t     %     Duplicate
    &+    %     Sum matrix with its transpose
    s     %     Sum each column. Gives a row vector
    tn:   %     Vector [1 2 ...] with the same size
    *     %     Multiply element-wise
    s     %     Sum of vector. This will be added to center entry of the matrix
    y     %     Duplicate matrix
    tn2/  %     Duplicate, get half its number of elements. Gives non-integer value
    )     %     Get center entry of the matrix, using linear index with implicit rounding
    +     %     Add center entry to sum of previous vector
    7M    %     Push index of center entry again
    (     %     Assgined new value to center of the matrix
    6Lt   %     Array [2 j1-1], twice. This will be used to remove shell
    3$)   %     Apply row and col indices to remove outer shell of the matrix
    tnq   %     Duplicate, number of elements, subtract 1. Falsy if matrix has 1 entry
          %   End do...while implicitly. The loop is exited when matrix has 1 entry
          % End if implicitly
          % Display stack implicitly

```

# Answer
> 4 votes
# Python 2.7, 229 bytes

This is my first attempt at something like this, so hopefully I followed all the rules with this submission. This is just a function which takes in a list of lists as its parameter. I feel like the sums and list comprehension could probably be shortened a little bit, but it was too hard for me. :D

```
def r(M):
  t=len(M)
  if t==1:return M[0][0]
  M[t/2][t/2]+=sum(a*b for k in [[l[x] for l in M]for x in range(0,t)]for a,b in enumerate(k,1))+sum([i*j for l in M for i,j in enumerate(l,1)])
  return r([p[+1:-1]for p in M[1:-1]])

```

Thx to Easterly Irk for helping me shave off a few bytes.

# Answer
> 3 votes
## C#, 257 bytes

here is a **non** esolang answer

```
void f(int[][]p){while(p.Length>1){int a=p.Length;int r=0;for(int i=0;i<a;i++)for(int j=0;j<a;j++)r+=(i+j+2)*p[i][j];p[a/2][a/2]+=r;p=p.Where((i,n)=>n>0&&n<p.Length-1).Select(k=>k.Where((i,n)=>n>0&&n<p.Length-1).ToArray()).ToArray();}Console.Write(p[0][0]);

```

ungolfed:

```
void f(int[][]p)
    {
        while (p.Length>1)
        {
            int a=p.Length;
            int r=0; //integer for number to add to middle
            for (int i = 0; i < a; i++)
                for (int j = 0; j < a; j++)
                    r +=(i+j+2)*p[i][j]; //add each element to counter according to their 1 based index
            p[a / 2][a / 2] += r; //add counter to middle
            p = p.Where((i, n) => n > 0 && n < p.Length - 1).Select(k => k.Where((i, n) => n > 0 && n < p.Length - 1).ToArray()).ToArray(); //strip outer shell from array
        }
        Console.Write(p[0][0]); //print last and only value in array
    }

```

# Answer
> 2 votes
# J, 66 bytes

```
([:}:@}."1@}:@}.]+(i.@,~=](]+*)<.@-:)@#*[:+/^:2#\*]+|:)^:(<.@-:@#)

```

Straight-forward approach based on the process described in the challenge.

`[:+/^:2#\*]+|:` gets the sum. `]+(i.@,~=](]+*)<.@-:)@#*` is a particularly ugly way to increment the center by the sum. `[:}:@}."1@}:@}.` removes the outer shell. There probably is a better way to do this.

## Usage

```
   f =: ([:}:@}."1@}:@}.]+(i.@,~=](]+*)<.@-:)@#*[:+/^:2#\*]+|:)^:(<.@-:@#)
   f _6
_6
   f _7 _1 8 , _4 _6 7 ,: _3 _6 6
2
   f 6 7 _2 5 1 , _2 6 _4 _2 3 , _1 _4 0 _2 _7 , 0 1 4 _4 8 ,: _8 _6 _5 0 2
_365
   f 8 3 5 6 6 _7 5 , 6 2 4 _2 _1 8 3 , 2 1 _5 3 8 2 _3 , 3 _1 0 7 _6 7 _5 , 0 _8 _4 _9 _4 2 _8 ,8 _9 _3 5 7 8 5 ,: 8 _1 4 5 1 _4 8
17611
   f (13 13 $ _9 _7 2 1 1 _2 3 _7 _3 6 7 1 0 _7 _8 _9 _2 7 _2 5 4 7 _7 8 _9 8 _4 4 _1 0 1 5 _3 7 1 _2 _9 4 8 4 8 1 _1 0 7 4 6 _9 3 _9 3 _9 _6 _8 _4 _8 _9 2 1 1 _8 8 2 6 _4 _8 _5 1 1 2 _9 3 7 2 5 _6 _1 2 _8 _5 _7 _4 _9 _2 5 0 2 _4 2 0 _2 _3 _6 _3 2 _9 8 1 _5 5 0 _4 _1 _9 _9 _9 _8 0 _5 _7 1 _2 1 _4 _1 5 7 _6 _9 4 _2 8 7 _9 _5 3 _1 1 8 4 _6 6 _3 _4 3 5 6 8 _2 5 _1 _7 _9 _1 7 _9 4 6 7 6 _8 5 1 0 _3 0 _3 _2 5 _4 0 0 0 _1 7 4 _9 _4 2)
_28473770

```

# Answer
> 2 votes
# Brachylog, 114 bytes

```
{l1,?hh.|:{:Im:I:?:{[L:I:M]h:JmN,Ll:2/D(IJ,M{$\:?c:{:{:ImN,I:1+:N*.}f+.}a+.}:N+.;'(DIJ),N.)}f.}f:7a$\:7a&.}.
brbr.

```

I'm suprised this even works to be honest. At least I realized that Brachylog really needs a "change value of that element" as a built-in though…

Usage example:

```
?- run_from_file('code.brachylog', '[[0:_2:_7:_7:_7]:[_3:_2:_2:_3:2]:[_8:4:139:_8:2]:[6:7:_1:8:4]:[5:7:8:7:_9]]', Z).
Z = 5321 .

```

### Explanation

More readable (and longer) version:

```
{l1,?hh.|:2f:7a$\:7a&.}.
:Im:I:?:3f.
[L:I:M]h:JmN,Ll:2/D(IJ,M:4&:N+.;'(DIJ),N.)
$\:?c:5a+.
:6f+.
:ImN,I:1+:N*.
brbr.

```

I'm just gonna explain roughly what each predicate (i.e each line except the first one which is Main Predicate + predicate 1) does:

* Main predicate + predicate 1 `{l1,?hh.|:2f:7a$\:7a&.}.` : If the input has only one row, then end the algorithm and return the only value. Else find all rows which satisfy predicate 2, then apply predicate 7 on the resulting matrix, then predicate 7 on the transposition, then call recursively.
* Predicate 2 `:Im:I:?:3f.` :Take the `I`th row of the matrix, find all values of that row which satisfy predicate 3 with `I` and the matrix as additional inputs.
* Predicate 3 `[L:I:M]h:JmN,Ll:2/D(IJ,M:4&:N+.;'(DIJ),N.)` : `L` is the row, `I` is the index of the row, `M` is the matrix. `N` is the `J`th element of `L`. If the length of `L` divided by 2 is equal to both `I` and `J`, then the output is the sum of `N` with the result of predicate 4 on the matrix. Otherwise the output is just `N`. This predicate essentialy recreates the matrix with the exception that the center element gets added to the sum.
* Predicate 4 `$\:?c:5a+.` : Apply predicate 5 on each row and column of the matrix, unify the output with the sum of the results.
* Predicate 5 `:6f+.` : Find all valid outputs of predicate 6 on the row, unify the output with the sum of the resulting list.
* Predicate 6 `:ImN,I:1+:N*.``N` is the `I`th value of the row, unify the output with `N * (I+1)`.
* Predicate 7 `brbr.` : Remove the first and last row of the matrix.

# Answer
> 2 votes
## APL, 56 chars

```
{{1 1↓¯1 ¯1↓⍵+(-⍴⍵)↑(⌈.5×⍴⍵)↑+/(⍵⍪⍉⍵)+.×⍳≢⍵}⍣(⌊.5×≢⍵)⊣⍵}

```

In English:

* `⍣(⌊.5×≢⍵)` repeat "half the size of a dimension rounded"-times
* `(⍵⍪⍉⍵)+.×⍳≢⍵` inner product of the matrix and its transpose with the index vector
* `(-⍴⍵)↑(⌈.5×⍴⍵)↑` transform result in matrix padded with 0s
* `1 1↓¯1 ¯1↓` removes outer shell

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


title: Write a chicken interpreter!

text:
# Question
Title: Write a chicken interpreter!
You have to write an interpreter for a cool language called Chicken!

You should read a Chicken program from a file, standard input, program or function arguments, or whatever is most convenient for your language, as well as input to the program.

You should print or return the result of interpreting the program according to the Chicken language specification.

More description about the language.

---

# Chicken Program Overview

Chicken operates on a single stack, which composes its entire memory model. As instructions are executed, the program will push and pop values from the stack, but there are also instructions that allow the program to modify other parts of the stack at will.

There are three segments in the stack:

1. The registers, at indices 0 and 1. Index 0 is a reference to the stack itself, and index 1 is a reference to the user input. Mostly used for instruction 6 (see below).
2. The loaded code: for each line of code there is cell in this segment that contains the number of "chicken"s in the line. This is padded with a 0 (opcode for terminate program) at the end.
3. The actual program stack, where values are pushed/popped as the program runs. Note that the segments are not isolated, which means that it is possible to create self-modifying code or execute code from this segment of the stack space.

# The Chicken ISA

Chicken's instruction set is based around the number of times the word "chicken" appears on each line of the program. An empty line terminates the program and prints the topmost value in the stack.

The Chicken instruction set, by number of "chicken"s per line:

1. Push the literal string "chicken" to the stack
2. Add top two stack values as natural numbers and push the result.
3. Subtract top two values as natural numbers and push the result.
4. Multiply top two values as natural numbers and push the result.
5. Compare two top values for equality, push 1 if they are equal and 0 otherwise.
6. Look at the next instruction to determine which source to load from: 0 loads from stack, 1 loads from user input. Top of stack points to address/index to load from the given source; load that value and push it onto stack. Since this is a double wide instruction, the instruction pointer skips the instruction used to determine the source.
7. Top of stack points to address/index to store to. The value below that will be popped and stored in the stack at the given index.
8. Top of stack is a relative offset to jump to. If the value below that is truthy, then the program jumps by the offset.
9. Interprets the top of the stack as ascii and pushes the corresponding character.
10. (10 + N) Pushes the literal number n-10 onto the stack.

---

# Example

Assume the program is:

```
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
(an empty line)

```

(A cat program. Note that the empty line is required because of the preceding line having 6 "chicken".)

*Input provided to Chicken program*

```
Chicken

```

*Output*

```
Chicken

```

The Chicken.js reference implementation.

---

# Error detection

The interpreter should leave an error and terminate when any word not "chicken" is present in the source.

---

Good luck!

# Answer
# Ruby, 335 bytes

Takes the input file name as a command line argument and takes user input (for instruction #6) from STDIN.

Because of Ruby "truthy" (everything except `false` and `nil`) being different from the Javascript "truthy" (Ruby truthy plus `0`, empty strings, etc.), there might be some edge cases where programs that work fine on a JS interpreter fail on this one because of instruction #8, such as if `""` is on the stack. I've fixed the biggest case, though, which is falsy `0`.

Works with the test program and the Hello World program on the Chicken website.

```
+(/^(#{c='chicken'}|\s)*$/m=~f=$<.read+"

")
s=[0,STDIN.read]+f.lines.map{|l|l.split.size};s[0]=s;i=1
s<<(s[i]<10?[->{c},->{x,y=s.pop 2;x+y},->{x,y=s.pop 2;x-y},->{s.pop*s.pop},->{s.pop==s.pop},->{s[s[i+=1]][s.pop]},->{s[s.pop]=s.pop;s.pop},->{l,k,j=s.pop 3;i+=j if k&&k!=0;l},->{s.pop.chr}][s[i]-1][]:s[i]-10)while s[i+=1]>0
$><<s.pop

```

## Explanation

The interpreter immediately starts off by running a regex match `/^(chicken|\s)*$/m` against the entire file (`$<.read`), which makes sure the file contains nothing but `chicken` and whitespace. In Ruby, this operator returns the index for the match, or `nil` if it wasn't found.

Two byte-saving tricks are used here: instead of directly matching `chicken`, the string substitution operator `#{}` is used instead to also assign that string to a variable for later (saves 1 byte), and when storing the contents of the file to a variable for processing, it appends two newlines to allow the `lines` function later to naturally append an extra `0` to the end of the instruction set. (Two are needed because of ignored trailing newline, which is necessary for the Chicken program.)

The error used is `NoMethodError: undefined method '+@' for nil:NilClass`, which is done by wrapping the regex match in parens and putting a `+` in front. If the file matches the pattern, you get `+0`, which evaluates to `0` and proceeds normally.

Next, the stack is assembled. The initial list must be created before the self-reference to the stack can be assigned, so a placeholder is used and then replaced. The instruction pointer is set to `1` instead of `2` because post-increment operators don't exist in Ruby.

Finally, it uses the lambda trick from @BassdropCumberwubwubwub to determine what to push on the stack next. If an operation doesn't push anything onto the stack, the interpreter simply pops an extra value so the stack stays the same. (This saves bytes over adding a push operation into every single lambda.)

**Ungolfed code:**

```
f = $<.read + "\n\n"
+(/^(chicken|\s)*$/m =~ f)
s = [0, STDIN.read] + f.lines.map{|l|l.split.size}
s[0] = s
i = 1

while s[i += 1] > 0
    if s[i] < 10
        s.push [
            ->{'chicken'},
            ->{
                x,y = s.pop 2
                x+y
                },
            ->{
                x,y = s.pop 2
                x-y
                },
            ->{s.pop*s.pop},
            ->{s.pop==s.pop},
            ->{s[s[i+=1]][s.pop]},
            ->{s[s.pop]=s.pop;s.pop},
            ->{
                l,k,j=s.pop 3
                i+=j if k&&k!=0
                l
                },
            ->{s.pop.chr}
        ][s[i] - 1][]
    else
        s.push(s[i] - 10)
    end
end

print s.pop

```
> 1 votes

# Answer
# Javascript ES6, 398 bytes

By far the longest golf I have ever done, I'm sure this can be improved but my brain doesn't recognize anything other than `chicken` at this point.

```
(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

```

I will edit the explanation in when my brain starts functioning again. Here's a slightly ungolfed version for now.
Outputs a falsey value (0) for everything which isn't `chicken`

```
(a,b)=>{
    for(c='chicken',s=[j=0,b,...A=a.split`
    `.map(m=>m.split(c).length-1)],i=A.length+2; // loop init
    j<A.length; // loop condition
    ( // everything else
        [
            _=>s[++i]=c,
            _=>s[--i]=s[i]+s[i+1],
            _=>s[--i]=s[i]-s[i+1],
            _=>s[--i]=s[i]*s[i+1],
            _=>s[--i]=s[i]==s[i+1],
            _=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],
            _=>s[s[i--]]=s[i--],
            _=>j+=s[--i]?s[--i+2]:0,
            _=>s[i]=String.fromCharCode(s[i])
        ][s[j+2]-1]
        ||(_=>s[++i]=s[j+1]-10)
    )(j++)
);
return /[^chicken \n]\w/g.test(a)?0:s[i]}

```

Try it here

```
f=
  (a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

i.innerHTML = f(`chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
`, 'Hello world!')
```

```
<pre id=i>
```
> 4 votes

---
Tags: code-golf, interpreter
---


title: Generating Picture Mazes

text:
# Question
Title: Generating Picture Mazes
# Challenge

Write a program/function that accepts an "image" and outputs a picture maze formed from that image.

# Input

Your program should accept two arguments:

* I, the image to form the maze from
* S, a boolean specifying whether or not to display the solution to the maze

I is given in the following form:

```
.......
.#####.
.#####.
#######
.#####.
.#####.
.......

```

where `#`'s are cells to be included in the solution path and `.`'s are cells to be excluded. You may swap out the `.`'s, `#`'s and newlines with any character of your choosing as long as they differ from each other. Alternatively, you may accept an actual bitmap of the input image.

# Output

Your resulting maze should be in the following form:

```
###############
#             #
# ### ####### #
# #.........# #
# #.#######.# #
# #.#.......# #
###.#.#########
....#.#........
#####.#.#######
#  ...#.....  #
# #.#######.# #
# #.........# #
# ####### ### #
#   #       # #
###############

```

where `#`'s denote walls, `.`'s denote portions of the path that are part of the solution, and spaces are paths excluded from the solution. The `.`'s may be replaced by spaces if S is false. Again, characters may be swaped with other characters of your choosing or you may output an actual bitmap of the maze with the solution highlighted.

# Additional Details

* Paths must be one cell wide (cannot have giant pool of empty space be the path)
* The maze must not contain any loops
* The maze must be fully connected (all cells must be reachable from the entrance/exit)
* The maze must be surrounded by walls (unless its an entrance/exit)
* The solution path must not include dead-ends
* There must be exactly 1 entrance and 1 exit for the maze
* The entrance and exit must be aligned to the edge of the grid and adjacent to a cell included in the solution path
* You may choose where the entrance and exit are placed
* You may assume that a valid path can be formed from the given input image

(Added for clarification) The diagram below shows how the solution path is correlated to the input image:

```
Input (I): |    Output:            |    Corresponding Cells:
           |                       |    (@'s denote #'s from I)
           |                       |
.......    |    ###############    |    ###############
.#####.    |    #             #    |    #             #
.#####.    |    # ### ####### #    |    # ### ####### #
#######    |    # #.........# #    |    # #@.@.@.@.@# #
.#####.    |    # #.#######.# #    |    # #.#######.# #
.#####.    |    # #.#.......# #    |    # #@#@.@.@.@# #
.......    |    ###.#.#########    |    ###.#.#########
           |    ....#.#........    |    .@.@#@#@.@.@.@.
           |    #####.#.#######    |    #####.#.#######
           |    #  ...#.....  #    |    #  @.@#@.@.@  #
           |    # #.#######.# #    |    # #.#######.# #
           |    # #.........# #    |    # #@.@.@.@.@# #
           |    # ####### ### #    |    # ####### ### #
           |    #   #       # #    |    #   #       # #
           |    ###############    |    ###############
           |                       |

```

# Test Cases

Watering can example from Wikipedia:

Input:

```
..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................

```

Output (S=false):

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

```

Output (S=true):

```
#####################################
#   #     #   #   #     #           #
# ### ### ### # # ##### ### ### ### #
#     # #   # # #         # #   # # #
# ### # ##### # ########### # ### # #
# # #         #.......    # # #   # #
# # # ### #####.# ###.### # ### ### #
#   # # #   #...# # #...# #   # #   #
# ### # #####.##### ###.##### # # ###
# #   #    ...#   #   #...    # # #..
### #######.### ### # ###.##### ###.#
#   #     #.#   #   #   #.#   # #...#
# ### #####.# ### #######.# # # #.# #
# #.......#.............#...# #...# #
# #.#####.#############.###.###.### #
#...#   #.......#.....#...#.#...# # #
#.### # #######.#.###.###.#.#.### # #
#.# # #  .......#...#.#...#...#     #
#.# # ###.#########.#.#.##### # #####
#.#   # #.#.......#.#...#...# # #   #
#.##### #.#.#####.#.#####.#.# ### # #
#.      #.#...#...#.#.....#.#   # # #
#.### ###.###.#.###.#.#####.####### #
#.  # # #.....#.#...#.#.....  #     #
#.# # # #######.#.###.#.##### # ### #
..# # # #...#...#.....#.....# #   # #
### # # #.#.#.#############.# ### # #
#   # # #.#...#.........#...# #   # #
##### # #.#####.#######.#.### ##### #
#     # #.#...#.......#.#...#       #
##### # #.#.#.#######.#.###.#########
#     #  ...#.........#.....  #     #
# ### ######### ############# # #####
# # #   #     # #       #     #     #
# # ######### # ####### ####### ### #
#             #                 #   #
#####################################

```

Bitmap example (same maze as above):

Input:  Output (S=false):  Output (S=true):

# Answer
> 12 votes
# Python 3, 1491 Bytes

I found this to be a fun project and very interesting (and somewhat lengthy). When I saw this, I was reminded of the summer I spent exclusively writing and improving a maze generation algorithm and instantly got to work on this.

After a while, I had an initial draft around 6000 bytes long and I spent the next couple of hours condensing it into the following program:

```
import random;R=range;L=len;T=sorted;P=print;N=random.randint;d='#';A=abs
def M(I,S):
 I=I.rsplit('\n');G=[[0]*(1+L(I[0])*2)for i in R(1+L(I)*2)]
 for i in R(L(I)):*G[1::2][i][1::2],=I[i]
 l=L(G[0])-2;c=E(G,l,-2);G[c][-1]=1;e=[c,l];c=E(G,1,2);G[c][:2]=1,1;s=[c,1]
 while s!=e:
  o=[];Q(G,s,e,-2,0,o,0);Q(G,s,e,0,2,o,1);Q(G,s,e,2,0,o,2);Q(G,s,e,0,-2,o,3);o=T(o,key=lambda x:(x[2],-x[1]))[0][0]
  if o==0:G[s[0]-1][s[1]]=1;s[0]-=2
  elif o==1:G[s[0]][s[1]+1]=1;s[1]+=2
  elif o==2:G[s[0]+1][s[1]]=1;s[0]+=2
  else:G[s[0]][s[1]-1]=1;s[1]-=2
  G[s[0]][s[1]]=1
 while 1 in['.'in x for x in G]:
  r=N(1,L(I))*2-1;c=N(1,L(I[0]))*2-1
  if G[r][c]in[1,2]:
   o=[];F(G,r-2,c,o,0);F(G,r,c+2,o,1);F(G,r+2,c,o,2);F(G,r,c-2,o,3)
   try:
    if o[0]==0:G[r-1][c]=2;G[r-2][c]=2
    elif o[0]==1:G[r][c+1]=2;G[r][c+2]=2
    elif o[0]==2:G[r+1][c]=2;G[r+2][c]=2
    else:G[r][c-1]=2;G[r][c-2]=2
   except:0
 *s,='#  '
 if S:s[1]='.'
 for x in G:P(*[s[y]for y in x],sep='')
def Q(G,s,e,x,y,o,a,n=0):
 c=lambda x,y:G[s[0]+x][s[1]+y]is d
 try:
  if c(x,y):
   try:n+=c(2*x,2*y)
   except:0
   try:n+=c(x+A(x)-2,y+A(y)-2)
   except:0
   try:n+=c(x-A(x)+2,y-A(y)+2)
   except:0
   o+=[[a,((s[0]+x-e[0])**2+(s[1]+y-e[1])**2)**.5,n]]
 except:0
def F(G,r,c,o,a):
 try:
  if G[r][c]is'.':o+=[a]
 except:0
def E(G,y,z):
 c=[]
 for x in R(1,L(G)-1,2):
  n=0
  try:n+=G[x-2][y]==d
  except:0
  try:n+=G[x+2][y]==d
  except:0
  n+=G[x][y+z]==d
  if G[x][y]==d:c+=[[x,n]]
 if L(c)>1:c=T(c,key=lambda x:x[1])
 return c[0][0]

```

Which is about as non-sensical to look at as an ascii-art maze is...

It's worth noting that, since the random function is not used until after the correct path has been found, no matter how many times the same input is given, the route from the start to the end will be the same and, while this program does work for the above examples, sometimes it will be unable to find a solution if it 'drives itself into a wall' so to speak.

When running the above examples, it gives this:

```
>>> M('''.......
.#####.
.#####.
#######
.#####.
.#####.
.......''',True)
###############
# # #   # #   #
# # # ### # # #
# #...#.....# #
# #.#.#.###.###
#  .#.#.#...# #
###.#.#.#.### #
....#.#.#.#....
# ###.#.#.#.###
# #...#.#.#.  #
# #.###.#.#.# #
# #.....#...# #
### ####### # #
#         # # #
###############
>>>

```

this:

```
>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',False)
#####################################
# #     #   # # #   # #   # # # # # #
# ### ##### # # # ### # ### # # # # #
#   # # #   #   # # # #   # # #   # #
### # # ### # ### # # # ### # ### # #
# #     #   # #         # # # # # # #
# ### ##### # # ##### ### # # # # # #
# # #   #   #     # #   # # # # # # #
# # # ##### # ##### ### # # # # # # #
# # # #         # # #         #
# # # # # # ##### # ### # ######### #
# #   # # # #   # # # # # # # # #   #
# # ####### # ### # # ### # # # # # #
#         # #           #   #     # #
### ##### # # ######### ### ### ### #
#     #   # # #   #   #     #   # # #
# ### ### # # # # # # ####### ### # #
#   # #   # # # # # # #   #       # #
# ##### # # # # # # # # # # # ##### #
#   #   # # # # # # # # #   #     # #
# ####### # # # # # # # #############
#   #     # # # # # # #         #   #
# ####### # # # # # # ##### ##### # #
#   #     # # # # # #           # # #
# ### ### # # # # # ######### ### ###
    # #   # # # # #         #   #   #
# ### # # # # # # ######### ##### ###
#   # # # # # # #                 # #
# # # ### # # # ################### #
# # # # # # # #               #     #
# ### # # # # ############# ### ### #
# # # #     #                     # #
# # ##### # # # ##### # # ##### ### #
# # #     # # #     # # #     #   # #
### ##### # ### # # # ##### # ### # #
#         #   # # # #     # #   # # #
#####################################
>>>

```

and this:

```
>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',True)
#####################################
#     #     # #   # # # # # # #     #
##### # # ### ### # # # # # # ### # #
# # # # # # # #     # # # # # # # # #
# # # ### # # ##### # # # # # # # ###
#   # #   # # #.......# #     #   # #
### # ### # # #.#####.# # ####### # #
#   # #   # #...#   #...#   # #   # #
### # ### # #.# # ### #.# ### ### # #
# # # # # #...# #   # #...  # #   #..
# # # # # #.# ### #######.### ### #.#
# #     #  .# #   # # #  .    # #...#
# # #######.##### # # ###.##### #.# #
#  .......#.#...........#...# #...# #
###.# ###.#.#.#########.###.# #.### #
#...# #  .#.#.#...#...#.....#...  # #
#.#######.#.#.#.#.#.#.#######.#######
#.    #  .#.#.#.#.#.#.#...#...#     #
#.#######.#.#.#.#.#.#.#.#.#.### #####
#.    #  .#.#.#.#.#.#.#.#...        #
#.#######.#.#.#.#.#.#.#.#############
#.    # #.#.#.#.#.#.#.#.....        #
#.##### #.#.#.#.#.#.#.#####.#########
#.  #    .#.#.#.#.#.#.......  # #   #
#.# # ###.#.#.#.#.#.########### # ###
..# # #  .#.#.#.#.#.........#   # # #
# # #####.#.#.#.#.#########.# ### # #
# # #    .#.#.#.#...........        #
#########.#.#.#.############### #####
#   #    .#.#.#.............# #     #
### # ###.#.#.#############.# ##### #
#     #  ...#...............      # #
##### # # ### # # # # ### # # ##### #
#     # #   # # # # #   # # #   #   #
####### # ### # # # ##### # ####### #
#       # #   # # #     # #       # #
#####################################
>>>

```

For anyone who'd like to try running this program themselves, use the command `M(Image, Show solution)`. I would recommend using the triple-quotes to input the image since otherwise there'll be a lot of back slashes or newline characters involved.

---
Tags: code-golf, ascii-art, graphical-output, path-finding, maze
---


title: I only pay with dollars

text:
# Question
Title: I only pay with dollars
As the title -- although discretely -- hints, I only pay with dollars.

## The challenge

Write a function/program that takes a string as input, which is a monetary value preceded by a symbol. `ex) £4.99`. Then, return that same amount converted to USD.

## Input

You will get a string as input. It will have the currency symbol followed by a number with two decimal places (which could be `.00`). There will either be decimal points `.` and/or commas `,` separating the number. The following currency symbols will come in the inputs:

> Euro: €
> Pound Sterling: £
> Yuan Renminbi: ¥

Also, there will be a comma or decimal point depending on the currency to separate the 'dollars' from the 'cents':

> Euro: #.###,##
> Pound Sterling: #,###.##
> Yuan Renminbi: #,###.##

## Output

You will convert the input from the currency determined by the symbol to USD, rounding to two decimal places. The output will be in the format `$#,###.##`, and there will of course be more numbers on the left of the output if need be (**EDIT: this means that there is an arbitrary number of commas in the output, just like in the input**). The currency exchange rate we will be using are below.

You can assume that the input contains a symbol that is only one of the above (`€ £ ¥ . ,`)--that it is always valid.

## Exchange rates

```
€1 : $1.10
£1 : $1.37
¥1 : $0.15

```

## Examples

```
Input:
€1,37
£4.00
¥2,782,122.78

Respective output:
$1.51
$5.48
$417,318.42

```

## Final words

1. If you use one of the above symbols (€, £, ¥), you may count them as 1 byte
2. This is code golf, so shortest code in bytes wins!

# Answer
# Pyth - ~~54~~ ~~53~~ ~~48~~ 47 bytes

Forgot about conditional application `W`.

```
.F"${:,.2f}"*v-tXWqhQ\€Q",.")\,@[1.1.15d1.37)Ch

```

Test Suite.
> 1 votes

# Answer
## Python 3.6 (pre-release), 87

```
lambda s:f"${int(s.translate({46:'',44:''})[1:])*[110,15,0,137][ord(s[0])%4]/1e4:,.2f}"

```

Uses f-strings to evaluate the result and format it.

`s.translate({46:'',44:''})` removes dots and commas from `s`, thus making it a valid `int` literal, then `int(...)` converts it into the actual `int` object.
> 5 votes

# Answer
## Convex, ~~56~~ ~~55~~ 54 bytes

```
(\®\.|,"ö)\e_\'.\++~\"€£¥"#[1.1_.27+.15]=*"%,.2f"\Ø'$\

```

Well, this can definitely be shortened. Try it online!

Saved a byte thanks to Lynn!

Explanation to come when I can get access to a computer.
> 4 votes

# Answer
# Java 7, ~~240~~ ~~227~~ ~~215~~ ~~211~~ ~~207~~ ~~202~~ ~~199~~ 196 bytes

(201 - 2 bytes because of the rule "*If you use one of the above symbols (€, £, ¥), you may count them as 1 byte*")
Thanks to *@Frozn* for saving a lot of bytes.

```
String c(String a){int c=a.charAt(0);return java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US).format(new Long(a.substring(1).replaceAll(",|\\.",""))*(c<'¥'?1.37:c>'¥'?1.1:.15)/100);}

```

**Ungolfed & test code:**

Try it here.

```
class Main{
  static String c(String a){
    int c = a.charAt(0);
    return java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US)
        .format(new Long(a.substring(1).replaceAll(",|\\.","")) *
                 (c < '¥'
                   ? 1.37
                   : c > '¥'
                     ? 1.1
                     : .15
                  ) / 100);
  }

  public static void main(String[] a){
    System.out.println(c("€1,37"));
    System.out.println(c("£4.00"));
    System.out.println(c("¥2,782,122.78"));
  }
}

```

**Output:**

```
$1.51
$5.48
$417,318.42

```
> 3 votes

# Answer
# JavaScript (ES6), 107

Simple and straightforward~~, probably more golfable~~

Note: tested in FireFox. Many browsers (especially mobile) have buggy support of `toLocaleString`

```
a=>(a.replace(/\D/g,'')/1e4*(a<'¥'?137:a>'€'?110:15)).toLocaleString('en',{style:'currency',currency:'USD'})

```

**TEST**

```
function test()
{
  var i=I.value
  var F=a=>(a.replace(/\D/g,'')/1e4*(a<'¥'?137:a>'€'?110:15)).toLocaleString('en',{style:'currency',currency:'USD'})
  O.textContent=F(i)
}

test()
```

```
<input id=I value='¥2,782,122.78' oninput='test()'>
<pre id=O></pre>
```
> 3 votes

# Answer
# Python 3.5, ~~137~~ ~~131~~ ~~121~~ ~~120~~ 117 bytes:

*(Thanks to Maltysen for a hint on saving 6 bytes `(137 -> 131)`!)*

```
lambda u:'${:,.2f}'.format(float(u[1:].translate([{44:''},{44:46,46:''}]['€'in u]))*{'€':1.1,'£':1.37,'¥':.15}[u[0]])

```

Try It Online! (Ideone)
> 3 votes

# Answer
# Python 3.5, ~~101~~ 98

```
lambda x:'${:,.2f}'.format(int(x[1:].translate({44:'',46:''}))*{'€':110,'£':137,'¥':15}[x[0]]/1e4)

```

The Euro, Pound, and Yen symbols are counted as 1 byte/character each, per the challenge rules.

Instead of translating among or interpreting thousands and decimal separators, these are just stripped out to give a plain digit string.

The digit string (after the currency symbol) is converted to an integer.

The currency symbol is used as an index into a dictionary of conversion rates; the conversion is performed by multiplying by the conversion rate and dividing by 10000.

The result is formatted with a leading dollar sign, two decimal places of precision, and commas for grouping.
> 1 votes

# Answer
# F#, 198 bytes

```
(s:string)="$"+(System.Double.Parse(if s.[0]='€'then s.[1..].Replace(".","").Replace(',','.')else s.[1..].Replace(",",""))*(if s.[0]='€'then 1.1 else if s.[0]='£'then 1.37 else 0.15)).ToString("N2")

```

Un-Golfed:

```
let IOnlyUseDollars(s : string) =
    let cur = s.[0]
    let str = if cur = '€' then s.[1..].Replace(".","").Replace(',', '.') else s.[1..].Replace(",","")
    let amt = System.Double.Parse(str)
    let dol = amt * (if cur = '€' then 1.1 else if cur = '£' then 1.37 else 0.15)
    "$" + dol.ToString("N2")

```

I'm still trying to figure out F#, so dealing with the thousands separators is taking up a lot of bytes.

According to the challenge rules, the Euro, Yen, and Pound symbols count as one byte each, despite how Unicode stores them internally.
> 1 votes

# Answer
## Python 3, 112 bytes NOT COMPETING

```
def c(x):x=x.translate(None,",.");print“$”+‘{:,.2f}’.format([1.1,1.37,0.15][“€£¥”.index(x[0])]*int(x[1:])/100,2)

```

This is not competing because I do not think that I am allowed to answer my own question.

Also, I have not yet had a chance to run this on a computer, but it seems to me like it should work. I will run it on a computer as soon as I have a chance.
> 0 votes

# Answer
# PHP, 117 bytes

```
function f($s){return'$'.number_format(ereg_replace('[^0-9]','',substr($s,1))*[E=>.011,P=>.0137,Y=>.0015][$s[0]],2);}

```

This makes use of a deprecated function; replace `ereg_replace('[^0-9]'` with `preg_replace('%[^\d]%'` to make the code fully modern; adds 1 byte.
> 0 votes

# Answer
# CJam, 54 bytes

```
'$q(\",."-de-2\"€£¥"#[1.1 1.37 .15]=*2mOs'./~\3/',*'.@

```

Try it here!
> 0 votes

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