title: Format a list of words

text:
# Question
Title: Format a list of words
Your challenge is to format a list of words across multiple lines that are no longer than a given number of characters, so that each line contains as many words as possible and no words are unnecessarily cut off.

## Input

The input will be a space-separated list of words and then a number that is at least 4.

## Output

The output should be the input words grouped into lines so that none of the lines contains more characters than the input number. The words should be output in the order they were input. The words should be separated by a comma and then a space, except at the end of each line, where the space isn't needed. If a word is too long to fit on a line, it should be cut off as little as possible while following the other rules, and "..." should be added to the end.

## Test cases

```
Input:
foo bar baz qux 12

Output:
foo, bar,
baz, qux

Input:
foo bar baz qux 5

Output:
foo,
bar,
baz,
qux

Input:
strength dexterity constitution intelligence wisdom charisma 10

Output:
strength,
dexterity,
consti...,
intell...,
wisdom,
charisma

Input:
quas wex exort 4

Output:
...,
wex,
e...

```

# Answer
# Unreadable, 2559 bytes

This challenge is eerily suited for Unreadable.

**The first version of this was 3379 bytes,** just to give you an idea of how much I golfed this.

The program accepts the input exactly as described in the challenge: a space-separated list of words (which may contain digits and punctuation marks, too), followed by a space and an integer that is at least 4 (lower numbers generate infinite loops).

> '""""""'""""""""'"""'""'""'""'""'""'""'"""'"""""'""'""""""'""'"""'""""""""""'""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'"""'"""""'"""""""'""""""'""""""""'"""'""""""""'"""""""'""""""""'"""'"""'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""""'""""'""""""'""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""'"""""'""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""""'""'"""'""'""'""'""'""'""'""'""'""'""'"""""""'""'"""'""""""'""'""'"""'"""""'""""""'"""""""'""""""""'"""'""""""""'"""""""'"""""""'""""""""'"""'""""""'""'"""'""'"""""""'""'"""'"""""'""""""'""'"""'""""""""'"""""""'""'"""'""""""'""""""'"""'""""""""'"""""""'"""'"""'""""""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""'""'"""'""'""'""'""""""'""""""""'"""'""'""'""'""'""'""'""""""'"""'"""'"""""'"""""""'""'"""""""'""""""""'"""'""""'""""'""""'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""""""'"""'""""""""'"""""""'"""'"""""""""'""""""'""'"""'"""""""'""'"""""""'""""""""'"""'""""""'"""'""""""""'"""""""'"""'"""'"""""'"""""""'""""""'""""""""'"""'""""""""'"""""""'""""""""'"""'"""'""""""'""'""'""'"""'"""""""""'"""""""'"""""""""'"""""""'""'""'""'"""'""""""'"""'""""""""'"""""""'"""'"""""""'"""'""""'""""'"""""""""'"""""""'""'""'""'"""'"'"""""""'""'""'""'""'""'"""'"""'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'"""""""'""""""""'"""'"""""""""'"""""""'""'"""'"'"""""""'""'""'""'""'"""'"""'""""'""""'"""""""""'"""""""'""'""'""'"""'"""'""""'""""'""""'""""'"""""'""""""""'"""""""'""""""'"""'""'"""""""'"""'"""'"""""""""'"""""""'""'"""'""""""'"""'""'"""""""'"""'"""'"""""'""'""""""'"""'""'"""""""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'"'"'"'"""""'"""""""'""""""'""""""""'"""'""'"""""""'""""""""'"""'""'""'"""""""'""'""'""'""'"""'"""""""""'"""""""'""'"""'"'"""""""'""'""'""'""'"""'"""'"'"""""""'""'""'"""'""""""""'""""""'"""'"""

## Explanation

I’m going to walk you through how the program processes the input `thyme horseradish peppermint 10`. The expected output is `thyme,\nhorser...,\npeppermint`.

First we start at cell #7 and read the entire input, but subtract 32 from every character so that spaces become zeros.

For obvious reasons, this leaves the running pointer (named *p* here, stored in cell #0) at the end. We use one while loop to find the last gap, which is the beginning of the number that defines the width of the output (cell #36 in this example).

We now want to decode the number (i.e. convert from decimal). The final result will be in both cells *t* and *r*. We rely on the fact that they start out at zero.

For every digit in the number, do the following:

* Set *t* to −15.
* In a while loop, decrement *r* (which contains the result so far) to −1 (because we need exactly *r* iterations, but since the decrement happens before it is checked as the while loop’s condition, decrementing to 0 would give one fewer iterations) and for each iteration, add 10 to *t*. Now *t* contains 10 times the previous result minus 15.
* Again in a while loop, decrement *\*p* to 0 and for each iteration, add 1 to *t*. After this *t* contains the correct intermediate result so far: the characters `'0'` to `'9'` have ASCII codes 48–57, so after the earlier subtraction of 32 they are 16–25, so we actually add 15–24 to *t*, which cancels with the −15 we set it to earlier. It is also important that this zeroes the cells that used to contain the digit characters so that the subsequent code can recognize the end of the list of words.
* Set *r* to the new intermediate result so that the next iteration finds it in *r*. (Note we do not need to read from *t* again, we can just use the last value from the previous while loop because we know that *\*p* can’t be zero, so it has run at least once.)

Finally, we use another simple while loop (decrementing *t* as the counter) to convert the number we just calculated into unary. We store a string of 1s going leftwards from cell #0. This relies on the fact that cell #1, our running pointer for this (*q*), starts out at 0. We get one fewer 1s because while loops in Unreadable are like that:

After this, we no longer need the value in *r*, so we re-use that cell for something else. We reset the pointers *p* and *q* and initialize some cells with ASCII codes of characters we need later. I’ve also labeled *c* and *s* which we will use later, and we will rely on the fact that *s* starts out at zero:

Hey, wait a minute. Why is cell #0 colored red?... Well, this is to highlight a sneaky trick. Remember we output one 1 too few? The trick is that we use the cell #0 as an “extension” to correct for that. This works because we know that *p* will never be 0. This way, the red block is now 10 cells wide, exactly the number we want. It also saves 9 characters to be able to initialize *q* to 1 instead of 0.

Now we enter the while loop that goes through the words and outputs them all.

Step 1: Find out whether the next word will fit into the current line. We do this by simply moving *p* to the right and *q* left with a while loop until *p* hits the next gap:

Now that *p* is on the *right* of the word, we can check whether this is the last word in the list by checking if *\*(p+1)* is zero. We also store that value (which in our example is 72 because it’s the “h” from “horseradish” minus 32) in *c* because we’ll need it again later. In this case, it isn’t zero, so we will need to output a comma along with the word, so the word is one character longer. Take account of this by decrementing *q* one more time. Finally, use another while loop to move *p* back to the beginning of the word.

We now know that the word will fit into the current line because *q* is pointing at a non-zero value, so all we have to do is:

* Move *p* forward through the word again, printing each character (plus 32, because all the ASCII codes are off by 32).
* If *c* is non-zero, print a comma (using the value in cell #5).
* Set *s* to a non-zero value to indicate to the next iteration that we are no longer at the beginning of a line and therefore need to output a space character before the next word. (We re-use the return value of the above print statement for this, which is 44 for the comma.)

Output so far: `thyme,`

Then the next iteration of the big loop starts. As before, we check whether the next word fits into the rest of the line by decrementing *q* as we go through the word from left to right. Note that *q* is still −5 from the previous iteration, keeping track of how many characters we’ve already printed in the current line. After counting the characters in “horseradish”, plus one for the comma, plus one because *s* is non-zero indicating that we need to output a space as well, *q* will have overshot the end of the block of 1s:

Now *q* points at a zero cell, which means that “horseradish” will not fit into the current line. What we do now depends on whether *s* is non-zero. In our case it is, which means we need to wrap to the next line. All we have to do for that is:

* Print a newline (using cell #3)
* Set *q* back to 1
* Set *s* to 0

Output so far: `thyme,\n`

For the next iteration, *p* is in the same place as before, so we will be looking at the same word again. As before, we count the characters in “horseradish”, set *c* to 80 again when we notice there’s another word after this one, decrement *q* for the comma, and rewind *p* back to the beginning of the word:

As in the previous iteration, we find that “horseradish” still doesn’t fit because *q* ends up on a cell that is zero. However, this time *s* is zero, which means we do something different than last time. We need to output some of the word, three dots and a comma. Our width is 10, so we need to output 6 characters of the word. Let’s see where we end up if we:

* Find the beginning of the red block of 1s. We can do this by going right because we know that *q* must be left of it.
* Increment *q* once more if we also need to output a comma (*c* ≠ 0).

The tape now looks like this:

I’ve marked a span of 6 cells here. As you can see, we need to output characters until *q* = −1. This is very code-efficient to check (basically, `while ((++q)+1) { ... }`). So:

* Print those characters (plus 32, because all the ASCII codes are off by 32) until *q* reaches −1. *p* will then be at cell 19, in the middle of the word “horseradish”.
* Print three dots. Since the print command returns its own argument, we can code-efficiently nest it (essentially, `print(print(print('.')))`). We take the ASCII value from cell #5 and add 2 to it to get the ASCII code of the dot.
* Move *p* to the end of the word. Since we know we can’t have already reached the end of the word (because the word was too long, and we had to remove at least 3 characters from it to fit the dots), this loop definitely has at least one iteration, so it’s shorter in code to have the body of the while loop calculate the ASCII value for the dot and then pass the return value of the while loop to the print functions.
* Print a comma if *c* is non-zero.

After all of this, we also print a newline (using cell #3) and set *q* back to 1. We can also set *s* to 0 even though it’s already 0, which makes this the same that we did previously when we wrapped to the next line (when *s* was non-zero), so to avoid repeating the code, we do it after the conditional that checks *s*.

Output so far: `thyme,\nhorser...,\n`

There is only one iteration left. This time, after counting the letters of the word, we get this:

This time, there is nothing after *p*, so we set *c* to 0 to indicate “no comma”, and accordingly we do not decrement *q* a further time. Since *q* now points at a non-zero cell, we know the word will fit, so the same code is executed as in the first iteration, except that this time *c* is zero, so it will simply not print the comma.

Output: `thyme,\nhorser...,\npeppermint`

In this walkthrough I did not include a case where the code would actually print a space, but I think it should be fairly clear now. If the code finds that the word fits (*\*q* ≠ 0) and *s* is non-zero, it will simply output a space before the word.
> 10 votes

# Answer
# JavaScript (ES6), 171

As an anonymous function returning the output as an array

(as this is generally allowed unless explicitly forbidden: meta meta)

```
s=>(s=s.split` `,n=s.pop()-1,t='',o=[],s.map((w,i)=>(w=w[n+=!s[i+1]]?w.slice(0,n-3)+'...':w,(t+w)[n-2]&&(t&&o.push(t.slice(1)),t=''),t+=` ${w},`)),o.push(t.slice(1,-1)),o)

```

```
f=s=>(s=s.split` `,n=s.pop()-1,t='',o=[],s.map((w,i)=>(w=w[n+=!s[i+1]]?w.slice(0,n-3)+'...':w,(t+w)[n-2]&&(t&&o.push(t.slice(1)),t=''),t+=` ${w},`)),o.push(t.slice(1,-1)),o)

// Less golfed
U=s=>(
  s=s.split` `,
  n=s.pop()-1,
  t='', // current line
  o=[], // output
  s.map( (w,i)=>(
    w=w[
      n+=!s[i+1] // space for 1 more char on the last line
    ]?w.slice(0,n-3)+'...':w, // change w if it is too long
    (t+w)[n-2]&& ( // if current line + w is too long, ouput t and reset current line
      t&&o.push(t.slice(1)),t=''
    ),
    t+=` ${w},`
  )),
  o.push(t.slice(1,-1)), // remove tailing comma on last line
  o
)

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

console.log(f("foo bar baz qux 12").join`\n`)
console.log(f("foo bar baz qux 5").join`\n`)
console.log(f("strength dexterity constitution intelligence wisdom charisma 10").join`\n`)
console.log(f("quas wex exort 4").join`\n`)
```

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

# Answer
## Python 2, 206 bytes

```
i=input().split()
l=int(i.pop())
i=[[w[:l-4]+'...',w][len(w)<l]+','for w in i][:-1]+[[w,w[:l-3]+'...'][len(w)>l]]
r=[i.pop(0)]
for w in i:
 if len(r[-1])+len(w)<l:r[-1]+=' '+w
 else:r+=[w]
print'\n'.join(r)

```
> 1 votes

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


title: Flip It, Flop It, Mean It

text:
# Question
Title: Flip It, Flop It, Mean It
# Overview

Given an image in plain PPM (P3) format as input, for each pixel `p` in the image, replace each of the following 4 pixels' red, green, and blue with the floored average value of the respective channels of all 4 pixels:

1. `p` itself
2. The pixel located at `p`'s location when the image is flipped vertically
3. The pixel located at `p`'s location when the image is flipped horizontally
4. The pixel located at `p`'s location when the image is flipped both vertically and horizontally

Output the resulting image in plain PPM (P3) format.

For further explanation, consider this 8x8 image, magnified to 128x128:

Let `p` be the red pixel. To calculate the new value for `p` (and the 3 blue pixels), the values of `p` and the 3 blue pixels will be averaged together:

```
p1 = (255, 0, 0)
p2 = (0, 0, 255)
p3 = (0, 0, 255)
p4 = (0, 0, 255)
p_result = (63, 0, 191)

```

---

# Examples

PPM: input, output

---

PPM: input, output

---

PPM: input, output

---

PPM: input, output

---

# Reference Implementation

```
#!/usr/bin/python

import sys
from itertools import *

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return list(izip_longest(*args, fillvalue=fillvalue))

def flatten(lst):
    return sum(([x] if not isinstance(x, list) else flatten(x) for x in lst), [])

def pnm_to_bin(p):
    w,h = map(int,p[1].split(' '))
    data = map(int, ' '.join(p[3:]).replace('\n', ' ').split())
    bin = []
    lines = grouper(data, w*3)
    for line in lines:
        data = []
        for rgb in grouper(line, 3):
            data.append(list(rgb))
        bin.append(data)
    return bin

def bin_to_pnm(b):
    pnm = 'P3 {} {} 255 '.format(len(b[0]), len(b))
    b = flatten(b)
    pnm += ' '.join(map(str, b))
    return pnm

def imageblender(img):
    h = len(img)
    w = len(img[0])
    for y in range(w):
        for x in range(h):
            for i in range(3):
                val = (img[x][y][i] + img[x][~y][i] + img[~x][y][i] + img[~x][~y][i])//4
                img[x][y][i],img[x][~y][i],img[~x][y][i],img[~x][~y][i] = (val,)*4
    return img

def main(fname):
    bin = pnm_to_bin(open(fname).read().split('\n'))
    bin = imageblender(bin)
    return bin_to_pnm(bin)

if __name__ == '__main__':
    print main(sys.argv[1])

```

This program takes a single filename as input, formatted like the output of `pngtopnm <pngfile> -plain`, and outputs a single line of PPM data separated by spaces.

---

# A Brief Description of the P3 Format

A PPM plaintext file generated from `pngtopnm <pngfile> -plain` will look like this:

```
P3
<width in pixels> <height in pixels>
<maximum value as defined by the bit depth, always 255 for our purposes>
<leftmost 24 pixels of row 1, in RGB triples, space-separated; like (0 0 0 1 1 1 ...)>
<next 24 pixels of row 1>
<...>
<rightmost (up to) 24 pixels of row 1>

<leftmost 24 pixels of row 2>
<next 24 pixels of row 2>
<...>
<rightmost (up to) 24 pixels of row 2>

<...>

```

This is the format that the example input and output files use. However, PNM is very loose about its formatting - *any* whitespace may separate values. You could replace all newlines in the above file with a single space each, and still have a valid file. For example, this file and this file are both valid, and represent the same image. The only other requirements are that the file must end with a trailing newline, and there must be `width*height` RGB triplets following the `255`.

---

# Rules

* This is , so the shortest valid solution wins.
* You may input and output PPM data formatted in any convenient and consistent manner, so long as it is valid according to the PPM format described above. The only exception is that you must use the plain (P3) format, and not the binary (P6) format.
* You must provide verification that your solution outputs the correct images for the above test images.
* All images will have a bit-depth of 8 bits.

Extra reading: Netpbm format wikipedia page

---

# Testing Snippet (thanks to Calvin's Hobbies for this)

```
function loadImage(t){if(t.files&&t.files[0]){var i=new FileReader;i.onload=function(t){function i(t){t.attr("width",img.width),t.width=img.width,t.attr("height",img.height),t.height=img.height;var i=t[0].getContext("2d");return i}img=$("<img>").attr("src",t.target.result)[0],ctxIn=i($("#input")),ctxIn.drawImage(img,0,0),ctxOut=i($("#output")),go()},i.readAsDataURL(t.files[0])}}function getPixel(t,i){return ctxIn.getImageData(t,i,1,1).data}function setPixel(t,i,e){ctxOut.fillStyle="rgb("+e[0]+","+e[1]+","+e[2]+")",ctxOut.fillRect(t,i,1,1)}function go(){if(void 0!==ctxOut)for(var t=0;t<img.width;t++)for(var i=0;i<img.height;i++){for(var e=new Array(3),g=getPixel(t,i),a=getPixel(img.width-t-1,i),r=getPixel(t,img.height-i-1),n=getPixel(img.width-t-1,img.height-i-1),h=0;h<e.length;h++)e[h]=Math.floor((g[h]+a[h]+r[h]+n[h])/4);setPixel(t,i,e)}}var img,ctxIn,ctxOut;
```

```
* {
    font-size: 100%;
    font-family: Arial, sans-serif;
}
```

```
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
Warning - runs very slowly on large images! 300x300 pixel maximum advised.<br><br>
<canvas id='input'>Your browser doesn't support the HTML5 canvas tag.</canvas><br><br>
Load an image: <input type='file' onchange='loadImage(this)'><br><br>
<canvas id='output'>Your browser doesn't support the HTML5 canvas tag.</canvas>
```

# Answer
# Pyth, 30 29 bytes

```
zjms.OdC.nM[JrR7.zKm_cd3J_J_K

```

My program expects all metadata on the first line, and the image data row by row on the lines after on stdin. To help, this is a small Python program to convert any valid PPM file into a PPM file my program can understand:

```
import sys
p3, w, h, d, *data = sys.stdin.read().split()
print(p3, w, h, d)
for i in range(0, int(w) * int(h), int(w)):
    print(" ".join(data[i:i+int(w)]))

```

Once you have the image data row by row the operations are really simple. First I read the image data into a list of lists of integers (`JrR7.z`), then I create the horizontally mirrored version by grouping every 3 integers and reversing them for every row (`Km_cd3J`). Then the vertically mirrored versions are simply `_J_K`, since we can just reverse rows.

I take all those matrices, flatten each of them into an 1d array with `.nM`, transpose with `C` to get a list of lists of each of the pixel components, average and truncate to int each of those lists (`ms.Od`), and finally print joined by newlines `j`.

Note that my program generates output in a different format (but still valid PPM). The demo images can be viewed in this imgur album.
> 3 votes

# Answer
## Bash (+ImageMagick), 64+1 = 65 bytes

```
C=convert;$C a -flip b;$C a -flop c;$C c -flip d;$C * -average e

```

Right tool for the job.

Must be run in a directory containing a single file `a` that contains the PPM data to transform. Since this filename is significant, I've added one byte to the byte count.

PNG thumbnail outputs (not sure why this is necessary because they're all the same anyway, but the question says so, so...):

Thanks to nneonneo for saving 2 bytes!
> 12 votes

# Answer
# Matlab, ~~106~~ ~~82~~ 80 bytes

```
i=imread(input(''))/4;for k=1:2;i=i+flipdim(i,k);end;imwrite(i,'p3.pnm','e','A')

```

The image is loaded as `n*m*3` matrix. Then we flip the matrix and added to itself for both axis, and write it again to a file.

---

I couldn't find a place to upload text files so big, so here are the PNG versions:
> 11 votes

# Answer
# Mathematica, 86 84 bytes

Thanks to DavidC for the advice. (saves 2 bytes)

```
Export[#2,⌊Mean@Join[#,(r=Reverse)/@#]&@{#,r/@#}&@Import[#,"Data"]⌋~Image~"Byte"]&

```

The first and second parameters are the paths to the input and output images, respectively.

---

### Test cases

```
f=%; (assign the function to symbol f)
f["penguin.pnm","penguin2.pnm"]
f["quintopia.pnm","quintopia2.pnm"]
f["peter.pnm","peter2.pnm"]

```

---

### Result

(PNG versions of the images are uploaded below)

```
Import["penguin2.pnm"]

```

```
Import["quintopia2.pnm"]

```

```
Import["peter2.pnm"]

```
> 9 votes

# Answer
# Julia, 157 bytes

```
using FileIO
s->(a=load(s);b=deepcopy(a);d=a.data;(n,m)=size(d);for i=1:n,j=1:m b.data[i,j]=mean([d[i,j];d[n-i+1,j];d[i,m-j+1];d[n-i+1,m-j+1]])end;save(s,b))

```

This is a lambda function that accepts a string containing the full path to a PPM file and overwrites it with the transformed image. To call it, assign it to a variable.

Ungolfed:

```
using FileIO

function f(s::AbstractString)
    # Load the input image
    a = load(s)

    # Create a copy (overwriting does bad things)
    b = deepcopy(a)

    # Extract the matrix of RGB triples from the input
    d = a.data

    # Store the size of the matrix
    n, m = size(d)

    # Apply the transformation
    # Note that we don't floor the mean; this is because the RGB values
    # aren't stored as integers, they're fixed point values in [0,1].
    # Simply taking the mean produces the desired output.
    for i = 1:n, j = 1:m
        b.data[i,j] = mean([d[i,j]; d[n-i+1,j]; d[i,m-j+1]; d[n-i+1,m-j+1]])
    end

    # Overwrite the input
    save(s, b)
end

```

Example outputs:
> 3 votes

# Answer
# python 2+PIL, 268

Now I massively use PIL, using image flipping and alpha blending

```
from PIL import Image
I=Image
B,T=I.blend,I.FLIP_TOP_BOTTOM
a=I.open(raw_input()).convert('RGB')
exec'b=a@I.FLIP_LEFT_RIGHT);c=a@T);d=b@T)'.replace('@','.transpose(')
x,y=a.size
print'P3',x,y,255
for r,g,b in list(B(B(B(a,b,0.5),c,0.25),d,0.25).getdata()):print r,g,b

```

Resulting images are available here
> 3 votes

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


# Question
Title: What is the shortest LOOP program that outputs 2016?
## LOOP

This challenge is based around a modified version of the programming language LOOP.

A program may be of any of the following forms:

* `P;Q`, where `P` and `Q` are subprograms
    + Subprogram P is executed, then subprogram Q is executed.
* `x++`, where `x` is a variable
    + Variable names are the letter `x` followed by a whole number (`0`, `1`, `2`, etc.). The value of variable x is incremented and assigned to variable x.
* `x:=y`, where `x` and `y` are variables
    + The value of variable y is assigned to variable x
* `LOOP x DO P END`, where `x` is a variable, and `P` is a subprogram
    + Subprogram P is executed a number of times equal to the value of x at the start of the loop. If the value of x changes during the loop, the number of iterations does not change.

Spaces and newlines may be inserted anywhere.

For this challenge, you may not use constants.

For example, the code
`LOOP x1 DO x2 := x2 + 1; LOOP x2 DO x1++ END END`
will set `x1` to the `x1`th triangle number, by adding 1, then 2 etc.

## Task

All variables are initialized to 0. The output of the program is the final value of x0, and the length of a program is the total count of increment/decrement/assignment/loop. The goal is to output 2016 with a program that is as short as possible.

Here is an interpreter for the modified language used in this challenge.

# Answer
> 1 votes
# Naive attempt, 15 statements

This uses the factorization of 2016 into `2^5*3^2*7`.

```
x1++;
x1++;
x2:=x1;
x2++;
x3:=x2+x2;
x3++;
LOOP x1 DO
LOOP x1 DO
LOOP x1 DO
LOOP x1 DO
LOOP x1 DO
LOOP x2 DO
LOOP x2 DO
LOOP x3 DO
x0++
END
END
END
END
END
END
END
END

```

I've gotten this to run on the provided interpreter by replacing things like `x1++;` with `x1:=x1+1;`, although I did not use "strict mode."

---
Tags: atomic-code-golf
---


title: Tic-tac-toe with only crosses

text:
# Question
Title: Tic-tac-toe with only crosses
### Introduction

Everyone knows the game tic-tac-toe, but in this challenge, we are going to introduce a little twist. We are only going to use **crosses**. The first person who places three crosses in a row loses. An interesting fact is that the maximum amount of crosses before someone loses, is equal to **6**:

```
X X -
X - X
- X X

```

That means that for a 3 x 3 board, the maximum amount is **6**. So for N = 3, we need to output 6.

Another example, for N = 4, or a 4 x 4 board:

```
X X - X
X X - X
- - - -
X X - X

```

This is an optimal solution, you can see that the maximum amount of crosses is equal to **9**. An optimal solution for a 12 x 12 board is:

```
X - X - X - X X - X X -
X X - X X - - - X X - X
- X - X - X X - - - X X
X - - - X X - X X - X -
- X X - - - X - - - - X
X X - X X - X - X X - -
- - X X - X - X X - X X
X - - - - X - - - X X -
- X - X X - X X - - - X
X X - - - X X - X - X -
X - X X - - - X X - X X
- X X - X X - X - X - X

```

This results in **74**.

### The task

The task is simple, given an integer greater than 0, output the *maximum* amount of crosses that can be placed with no three X's adjacent in a line along a row, column or diagonally.

### Test cases

```
N     Output
1     1
2     4
3     6
4     9
5     16
6     20
7     26
8     36
9     42

```

More information can be found at https://oeis.org/A181018.

### Rules

* This is , so the submission with the least amount of bytes wins!
* You may provide a function or a program.

# Answer
## Pyth, ~~57~~ ~~51~~ 49 bytes

```
L.T.e+*]Ykbbsef!s.AMs.:R3ssmyBdsm_BdCBcTQsD^U2^Q2

```

Like @PeterTaylor's CJam solution, this is brute-force, so it runs in O(n22n2) time. The online interpreter doesn't finish within a minute for n=4.

Try it here for N\<4.

Try the diagonals function.

```
L.T.e+*]Ykbb         y(b): diagonals of b (with some trailing [])
s e                  sum of the last (with most ones) array such that
f                    filter lambda T:
 ! s .AM                none of the 3 element sublists are all ones
   s .:R3               all 3 element sublists
   s s                  flatten
   myBd                 add the diagonals
   sm_B d               add the vertically flipped array and transpose
   CBcTQ                array shaped into Q by Q square, and its transpose
 sD ^U2 ^Q2             all binary arrays of length Q^2 sorted by sum

```
> 11 votes

# Answer
## CJam (58 56 bytes)

```
2q~:Xm*{7Yb#W=}:F,Xm*{ee{~0a@*\+}%zS*F},_Wf%:z&Mf*1fb:e>

```

This is incredibly slow and uses a lot of memory, but that's for you.

### Dissection

```
2q~:Xm*        e# Read input into X and find Cartesian product {0,1}^X
{7Yb#W=}:F,    e# Filter with a predicate F which rejects arrays with a 111
Xm*            e# Take the Cartesian product possible_rows^X to get possible grids
{              e# Filter out grids with an anti-diagonal 111 by...
  ee{~0a@*\+}% e#   prepending [0]*i to the ith row
  zS*F         e#   transposing, joining on a non-1, and applying F
},
_Wf%:z         e# Copy the filtered arrays and map a 90 degree rotation
&              e# Intersect. The rotation maps horizontal to vertical and
               e# anti-diagonal to diagonal, so this gets down to valid grids
Mf*            e# Flatten each grid
1fb            e# Count its 1s
:e>            e# Select the maximum

```

The number of valid rows is a tribonacci number and is \\$\Theta(a^X)\\$ where \\$a\\$ is the tribonacci constant, \\$1.83928675\ldots\\$. The number of grids generated in the Cartesian product is \\$\Theta(a^{X^2})\\$; the second filter will reduce the number somewhat, but the intersection is still probably \\$\Theta(a^{X^4})\\$.

---

An "efficient" approach ("merely" \\$O(X a^{3X})\\$) uses dynamic programming. Ungolfed in Java:

```
public class A181018 {
    public static void main(String[] args) {
        for (int i = 1; i < 14; i++) {
            System.out.format("%d:\t%d\n", i, calc(i));
        }
    }

    private static int calc(int n) {
        if (n < 0) throw new IllegalArgumentException("n");
        if (n < 3) return n * n;

        // Dynamic programming approach: given two rows, we can enumerate the possible third row.
        // sc[i + rows.length * j] is the greatest score achievable with a board ending in rows[i], rows[j].
        int[] rows = buildRows(n);
        byte[] sc = new byte[rows.length * rows.length];
        for (int j = 0, k = 0; j < rows.length; j++) {
            int qsc = Integer.bitCount(rows[j]);
            for (int i = 0; i < rows.length; i++) sc[k++] = (byte)(qsc + Integer.bitCount(rows[i]));
        }

        int max = 0;
        for (int h = 2; h < n; h++) {
            byte[] nsc = new byte[rows.length * rows.length];
            for (int i = 0; i < rows.length; i++) {
                int p = rows[i];
                for (int j = 0; j < rows.length; j++) {
                    int q = rows[j];
                    // The rows which follow p,q cannot intersect with a certain mask.
                    int mask = (p & q) | ((p << 2) & (q << 1)) | ((p >> 2) & (q >> 1));
                    for (int k = 0; k < rows.length; k++) {
                        int r = rows[k];
                        if ((r & mask) != 0) continue;

                        int pqrsc = (sc[i + rows.length * j] & 0xff) + Integer.bitCount(r);
                        int off = j + rows.length * k;
                        if (pqrsc > nsc[off]) nsc[off] = (byte)pqrsc;
                        if (pqrsc > max) max = pqrsc;
                    }
                }
            }

            sc = nsc;
        }

        return max;
    }

    private static int[] buildRows(int n) {
        // Array length is a tribonacci number.
        int c = 1;
        for (int a = 0, b = 1, i = 0; i < n; i++) c = a + (a = b) + (b = c);

        int[] rows = new int[c];
        int i = 0, j = 1, val;
        while ((val = rows[i]) < (1 << (n - 1))) {
            if (val > 0) rows[j++] = val * 2;
            if ((val & 3) != 3) rows[j++] = val * 2 + 1;
            i++;
        }

        return rows;
    }
}

```
> 13 votes

# Answer
# C, ~~460~~ ~~456~~ ~~410~~ ~~407~~ ~~362~~ ~~351~~ 318 bytes

This is a really bad answer. It's an *incredibly* slow brute force approach. ~~I'm trying to golf it a bit more by combining the `for` loops.~~

```
#define r return
#define d(x,y)b[x]*b[x+y]*b[x+2*(y)]
n,*b;s(i){for(;i<n*(n-2);++i)if(d(i%(n-2)+i/(n-2)*n,1)+d(i,n)+(i%n<n-2&&d(i,n+1)+d(i+2,n-1)))r 1;r 0;}t(x,c,l,f){if(s(0))r 0;b[x]++;if(x==n*n-1)r c+!s(0);l=t(x+1,c+1);b[x]--;f=t(x+1,c);r l>f?l:f;}main(c,v)char**v;{n=atol(v[1]);b=calloc(n*n,4);printf("%d",t(0,0));}

```

## Test Cases

```
$ ./a.out 1
1$ ./a.out 2
4$ ./a.out 3
6$ ./a.out 4
9$ ./a.out 5
16$

```

## Ungolfed

```
n,*b; /* board size, board */

s(i) /* Is the board solved? */
{
    for(;i<n*(n-2);++i) /* Iterate through the board */
            if(b[i%(n-2)+i/(n-2)*n]&&b[i%(n-2)+i/(n-2)*n+1]&&b[i%(n-2)+i/(n-2)*n+2] /* Check for horizontal tic-tac-toe */
                    || b[i] && b[i+n] && b[i+2*n] /* Check for vertical tic-tac-toe */
                    || (i%n<n-2
                            && (b[i] &&b [i+n+1] && b[i+2*n+2] /* Check for diagonal tic-tac-toe */
                                    || b[i+2*n] && b[i+n+1] && b[i+2]))) /* Check for reverse diagonal tic-tac-toe */
                    return 1;
    return 0;
}

t(x,c,l,f) /* Try a move at the given index */
{
    if(s(0)) /* If board is solved, this is not a viable path */
            return 0;
    b[x]++;
    if(x==n*n-1) /* If we've reached the last square, return the count */
            return c+!s(0);

    /* Try it with the cross */
    l=t(x+1,c+1);

    /* And try it without */
    b[x]--;
    f=t(x+1,c);

    /* Return the better result of the two */
    return l>f?l:f;
}

main(c,v)
char**v;
{
    n=atol(v[1]); /* Get the board size */
    b=calloc(n*n,4); /* Allocate a board */
    printf("%d",t(0,0)); /* Print the result */
}

```

---

Edit: Declare int variables as unused parameters; remove y coordinate, just use index; move variable to parameter list rather than global, fix unnecessary parameters passed to `s()`; combine for loops, remove unnecessary parentheses; replace `&&` with `*`, `||` with `+`; macro-ify the 3-in-a-row check
> 4 votes

# Answer
# C 263 ~~264 283 309~~

**Edit** A few bytes saved thx @Peter Taylor - less than I hoped. Then 2 bytes used to allocate some more memory, now I can try larger size, but it's becoming very time consuming.

**Note** While adding the explanation, I found out that i'm wasting bytes keeping the grid in the R array - so that you can to see the solution found ... it's not requested for this challenge!!
I removed it in the golfed version

A golfed C program that can actually find the answer for n=1..10 in reasonable time.

```
s,k,n,V[9999],B[9999],i,b;K(l,w,u,t,i){for(t=u&t|u*2&t*4|u/2&t/4,--l; i--;)V[i]&t||(b=B[i]+w,l?b+(n+2)/3*2*l>s&&K(l,b,V[i],u,k):b>s?s=b:0);}main(v){for(scanf("%d",&n);(v=V[i]*2)<1<<n;v%8<6?B[V[k]=v+1,k++]=b+1:0)V[k]=v,b=B[k++]=B[i++];K(n,0,0,0,k);printf("%d",s);}

```

My test:

> 7 -\> 26 in 10 sec
> 8 -\> 36 in 18 sec
> 9 -\> 42 in 1162 sec

**Less golfed** and trying to explain

```
#include <stdio.h>

int n, // the grid size
    s, // the result
    k, // the number of valid rows
    V[9999], // the list of valid rows (0..to k-1) as bitmasks
    B[9999], // the list of 'weight' for each valid rows (number of set bits)
    R[99],  // the grid as an array of indices pointing to bitmask in V
    b,i; // int globals set to 0, to avoid int declaration inside functions

// recursive function to fill the grid
int K(
  int l, // number of rows filled so far == index of row to add
  int w, // number of crosses so far
  int u, // bit mask of the preceding line (V[r[l-1]])
  int t, // bit mask of the preceding preceding line (V[r[l-2]])
  int i) // the loop variables, init to k at each call, will go down to 0
{
  // build a bit mask to check the next line
  // with the limit of 3 crosses we need to check the 2 preceding rows
  t = u&t | u*2 & t*4 | u/2 & t/4;
  for (; i--; )// loop on the k possibile values in V
  {
    R[l] = i; // store current row in R
    b = B[i] + w; // new number of crosses if this row is accepted
    if ((V[i] & t) == 0) // check if there are not 3 adjacent crosses
      // then check if the score that we can reach from this point
      // adding the missing rows can eventually be greater
      // than the current max score stored in s
      if (b + (n + 2) / 3 * 2 * (n - l - 1) > s)
        if (l > n-2) // if at last row
          s = b > s ? b : s; // update the max score
        else  // not the last row
          K(l + 1, b, V[i], u, k); // recursive call, try to add another row
  }
}

int main(int j)
{
  scanf("%d", &n);

  // find all valid rows - not having more than 2 adjacent crosses
  // put valid rows in array V
  // for each valid row found, store the cross number in array B
  // the number of valid rows will be in k
  for (; i<1 << n; V[k] = i++, k += !b) // i is global and start at 0
    for (b = B[k] = 0, j = i; j; j /= 2)
      b = ~(j | -8) ? b : 1, B[k] += j & 1;
  K(0,0,0,0,k); // call recursive function to find the max score
  printf("%d\n", s);
}

```
> 4 votes

# Answer
# Ruby, 263 bytes

This is also a brute force solution and faces the same problems as the C answer by Cole Cameron, but is even slower since this is ruby and not C. But hey, it's shorter.

```
c=->(b){b.transpose.all?{|a|/111/!~a*''}}
m=->(b,j=0){b[j/N][j%N]=1
x,*o=b.map.with_index,0
c[b]&&c[b.transpose]&&c[x.map{|a,i|o*(N-i)+a+o*i}]&&c[x.map{|a,i|o*i+a+o*(N-i)}]?(((j+1)...N*N).map{|i|m[b.map(&:dup),i]}.max||0)+1:0}
N=$*[0].to_i
p m[N.times.map{[0]*N}]

```

Test cases

```
$ ruby A181018.rb 1
1
$ ruby A181018.rb 2
4
$ ruby A181018.rb 3
6
$ ruby A181018.rb 4
9
$ ruby A181018.rb 5
16

```

Ungolfed

```
def check_columns(board)
  board.transpose.all? do |column|
    !column.join('').match(/111/)
  end
end

def check_if_unsolved(board)
  check_columns(board) && # check columns
    check_columns(board.transpose) && # check rows
    check_columns(board.map.with_index.map { |row, i| [0] * (N - i) + row + [0] * i }) && # check decending diagonals
    check_columns(board.map.with_index.map { |row, i| [0] * i + row + [0] * (N - i) }) # check ascending diagonals
end

def maximum_crosses_to_place(board, index=0)
  board[index / N][index % N] = 1 # set cross at index
  if check_if_unsolved(board)
    crosses = ((index + 1)...(N*N)).map do |i|
      maximum_crosses_to_place(board.map(&:dup), i)
    end
    maximum_crosses = crosses.max || 0
    maximum_crosses + 1
  else
    0
  end
end

N = ARGV[0].to_i
matrix_of_zeros = N.times.map{ [0]*N }

puts maximum_crosses_to_place(matrix_of_zeros)

```
> 2 votes

# Answer
# Haskell, 143 bytes

In some ways this is not done, but I had fun so here goes:

* Because checking for the horizontal "winning" pattern returns invalid if applied across different rows, input of N\<3 returns 0
* The "arrays" are integers unpacked into bits, so easily enumerable
* ((i ! x) y) gives the ith bit of x times y, where negative indices return 0 so the range can be constant (no bounds checking) and fewer parentheses when chained
* Because the bounds are not checked, it checks 81\*4=324 patterns for *every* possible maximum, leading to N=3 taking my laptop 9 seconds and N=5 taking too long for me to let it finish
* Boolean logic on 1/0 is used for T/F to save space, for example (\*) is &&, (1-x) is (not x), etc.
* Because it checks integers instead of arrays, (div p1 L)==(div p2 L) is needed to make sure a pattern isn't checked across different rows, where L is the row length and p1, p2 are positions
* The value of a possible maximum is its Hamming Weight

Here's the code:

```
r=[0..81]
(%)=div
s=sum
i!x|i<0=(*0)|0<1=(*mod(x%(2^i))2)
f l=maximum[s[i!x$1-s[s[1#2,l#(l+l),(l+1)#(l+l+2),(1-l)#(2-l-l)]|p<-r,let  a#b=p!x$(p+a)!x$(p+b)!x$s[1|p%l==(p+mod b l)%l]]|i<-r]|x<-[0..2^l^2]]

```
> 1 votes

---
Tags: code-golf, sequence, combinatorics, grid, tic-tac-toe
---


title: Quinean Regex Tester

text:
# Question
Title: Quinean Regex Tester
This challenge is pretty simple. As input, you take in a regular expression.

Then, you output a truthy/falsey of whether or not your source code matches the regular expression. It's that simple! Just two more things:

* No quine builtins; you may, however, access the code's source code by file IO, etc.
* This is , so shortest code in **bytes** wins!

## Example

If your source code was say, `abc`, an input of `a\wc` would return true and an input of `a\dc` would return false.

# Answer
# Z shell, 12 bytes

```
grep "$@"<$0

```

Zsh conditionals understand only exit codes, and the scripts exits with 0 or 1 accordingly.

In addition, this prints a non-empty string (the source code) for a match and an empty one for a mismatch, which could be as truthy/falsy values in combination with `test`/`[`.

The program reads its own file, but according to this comment by the OP, this is allowed.
> 14 votes

# Answer
# JavaScript (ES6), 39

```
(f=_=>!!`(f=${f})()`.match(prompt()))()

```
> 10 votes

# Answer
# Python 3, 119 bytes

This just *looks* cooler, IMO (and it doesn't read the file).

```
(lambda i:print(bool(__import__('re').search(input(),i))))("(lambda i:print(bool(__import__('re').search(input(),i))))")

```

---

# Python 3, 67 bytes

```
print(bool(__import__('re').search(input(),open(__file__).read())))

```

Added after reading this comment.
> 8 votes

# Answer
# Julia, ~~64~~ 54 bytes

```
r=readline;show(ismatch(Regex(r()),open(r,@__FILE__)))

```

Julia regular expressions use PCRE. While reading the source code of the file is a standard loophole for quines, in this case it has been explicitly allowed. Takes input with no trailing newline.
> 7 votes

# Answer
# Japt, 22 bytes

```
"+Q ³sAJ fU"+Q ³sAJ fU

```

Standard quine framework with a few bytes added to fit this challenge. Truthy = match(es), falsy = null. Try it online!

```
         // Implicit: U = input string, A = 10, J = -1, Q = quotation mark
"..."+Q  // Take this string and concatenate a quotation mark.
³        // Repeat three times.
sAJ      // Slice off the first 10 and last 1 chars.
fU       // Match U to the result.

```
> 3 votes

# Answer
# Perl, 21 bytes

```
open 0;$_=<0>=~$_

```

17 bytes plus 4 bytes for `-pl0`. Run like this:

```
echo open | perl -pl0 quinean

```

The source file must contain only the code above (no shebang, no trailing newline). Outputs `1` if the regex matches and the empty string if it doesn't (the empty string is falsey in Perl).

---

Four bytes can be saved if the input is guaranteed not to end in a newline:

```
open 0;say<0>=~<>

```

Run like this:

```
echo -n open | perl -M5.010 quinean

```

`say` requires Perl 5.10+ and must be enabled with `-M5.010`. According to Meta, "the `-M5.010`, when needed, is free," giving a score of 17 bytes.

## How it works

This is a simple variation on the standard "cheating" quine:

```
open 0;print<0>

```

This opens the file named in `$0` and reads the contents with `<0>`.

`$_=<0>=~$_` reads one line from the source file, does a regex match against the contents of `$_` (which were read by the `-p` flag), and assigns the result to `$_`. `-p` prints `$_` automatically at the end.
> 3 votes

# Answer
# Jolf, ~~18~~ 15 bytes

Supports the JS flavour of RegEx, I hope that's okay. Try it here!.

```
 h$code.value#i

```

Commented:

```
  $code.value#      the document's element "code" (the program container)
_h            i     and output if it has (matches) the input string (i.e. regex)

```
> 2 votes

# Answer
# Mathematica, 63 bytes

```
StringMatchQ[ToString[#0, InputForm], RegularExpression[#1]] &

```

Note the trailing space. Uses the standard Mma quine mechanism, and tests if it matches the regex.
> 2 votes

# Answer
# , 14 chars / 26 bytes (non-competitive)

```
⟮‼(ⒸⅩ222+ᶈ0)đï

```

`Try it here (Firefox only).`

Using a version with bug fixes written after the challenge.

# Explanation

```
⟮‼(ⒸⅩ222+ᶈ0)đï // implicit: ï=input
⟮               // copy block: copy following code for later use
 (ⒸⅩ222+ᶈ0)   // take convert 10222 to char, add stuff inside copy block
‼           đï // check if input matches resulting string
               // implicit output

```

NOTE: Copy blocks are NOT quine operators. They are meant to be more versatile alternatives to variable declarations.
> 1 votes

---
Tags: code-golf, quine, regular-expression
---


title: Hexadecimal of a character

text:
# Question
Title: Hexadecimal of a character
Given a unicode character `C` (or the first character of a string input), output that character's hex representation. Case does not matter. The output ranges from `\u0000` to `\u9999`.

Test cases

```
A => 41  (65_10 === 41_16)
ʣ => 2A3 (675_10 === 2A3_16)
Ω => 3A9 (937_10 === 3A9_16)
7 => 37  (55_10 === 37_16)
(null byte) => 0 (0_10 === 0_16)

```

-50% byte bonus if you output the javascript escape character `\uXXXX` of the character `C`, e.g. `g => \u0067` and `~ => \u007E`

# Answer
# Jolf, 3 bytes

Try it here!

```
~Ti

```

Compiles to `var i=prompt("i = ");(i).charCodeAt().toString(16);`

## Bonus, 13 - 50% = 6.5 bytes

Try it here!

```
"\\u%"pq~Ti40
"\\u "        prefix
    %         interpolate with
        ~Ti    you know what this is
      pq   40  pad with 4 0's

```
> 3 votes

# Answer
## CJam, ~~5~~ ~~20~~ 18 bytes

```
{iGb{A,6,'Af++=}%}

```

`i` converts to integer, `G` pushes 16, `b` is base conversion.

... and CJam has no way to use 0-9A-Z instead of base-converting to numbers? That's not annoying at all.

```
{          }%   map over number-digits
 A,             generate the digits 0-9
   6,'Af+       generate the "digits" A-F
         +      concat
          =     array-index into the newly generated array

```

Thanks to @MartinBüttner for saving 2 bytes!
> 3 votes

# Answer
# Julia, 14 bytes

Interestingly, this is 14 bytes with and without the bonus.

No bonus:

```
c->hex(Int(c))

```

Bonus:

```
c->"\\u"lpad(hex(Int(c)),4,0)

```

Both are lambda functions that accept `Char`s and return strings. To call a lambda, assign it to a variable.

We get the code point associated with the `Char` using `Int()`, then convert to hexadecimal using `hex()`. For the bonus, we left pad to 4 characters with zeros and prepend `\\u`. The backslash needs to be escaped in the string.
> 3 votes

# Answer
# CJam, 5.5 bytes

```
"\u%04X"qe%

```

The code is **11 bytes** long and qualifies for the **-50%** bonus. Try it online in the CJam interpreter.

### How it works

```
"\u%04X"     e# Push that format string, i.e., a literal "\u", followed by
             e# an integer in hexadecimal, 0-padded to 4 characters.
        q    e# Read all input.
         e%  e# Apply string formatting.

```

The online interpreter will happily treat the input string as the code point of its sole character. This does *not* work in the Java interpreter, so it might be a feature or a bug.
> 3 votes

# Answer
# Pyth - 4 bytes

```
.HCz

```

Test Suite.

Pyth doesn't do unicode for string conversions, instead uses ISO-8859, so cost one more byte.

```
.H            Hex representation
 C            Unicode code point
  z           Input string

```
> 2 votes

# Answer
# TeaScript, 5 bytes

```
xcT16

```

I'm very sure I have a unicode shortcut for 16

Try it online
> 2 votes

# Answer
# JavaScript ES6, ~~30~~ 54 / 2 = 27 bytes

```
s=>"\\u"+("000"+s.charCodeAt().toString(16)).slice(-4)

```

The bonus helped a bit

Try it online at ESFiddle (all browsers work)
> 2 votes

# Answer
# Mathematica, 50 - 50% = 25 bytes

```
"\u"<>IntegerString[First@ToCharacterCode@#,16,4]&

```

Ignore the error. Mathematica does not recognize the escape code `\u`, so just escapes the `\` and gives a `Syntax:stresc` message.
> 2 votes

# Answer
# Japt, 5 bytes

```
Uc sG

```

Very simple. Try it online!

### How it works

```
Uc sG  // Implicit: U = input, G = 16
Uc     // Take the char code of U.
   sG  // Turn it into a base-16 string.
       // Implicit: output last expression

```

### Bonus version, 20 bytes * 0.5 = 10

```
"\\u{'0³+Uc sG)t0-4

```

Not as simple. Try it online!

### How it works

```
          // Implicit: U = input, G = 16
"\\u{     // Take the string "\u", and add:
 '0³+     //  Take 3 "0"s, plus
 Uc sG)   //  the hex char code of the input.
 t0-4     //  Take the last 4 chars.
          // Implicit: output last expression

```
> 1 votes

# Answer
## Python 2, 27/2 = 13.5 bytes

```
lambda x:r'\u%04X'%(ord(x))

```

No online link because apparently ideone's Python 2 version doesn't support Unicode string literals.
> 1 votes

# Answer
# , 3 chars / 8 bytes

```
ï⒞ⓧ

```

`Try it here (Firefox only).`

Superbly simple. Convert to charcode, then to hex.
> 1 votes

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


title: Format the reputation

text:
# Question
Title: Format the reputation
You probably do know that the different reputation levels on Stack Exchange are formatted differently when seen from the questions page / a post. There're all the rep-formatting rules:

* if a user has 1 to 999 (one to three digits) rep, it's left as-is.
* if a user has 1000 to 9999 rep (four digits), it receives the comma as a separator: `9,999`
* if a user has 10000 to 99999 rep (five digits), it's shortened and rounded. I.e., 16741 rep is formatted as `16.7k`, notice the dot separator unlike the comma for the lower rep (previous point).

1. 16750 will already result `16.8k` (since this seems to be fixed)
    2. 16941 results in `16.9k`, 16950 rounds up to `17k`, as well as does 17014, for example.
    3. 99941 rounds to `99.9k`, 99950 rounds to `100k` (this is something I actually hate with the rep-rounding on SE, because 100,000 is such a milestone, and 99950 is nowhere near).
* If a user has 100000 to 999999 rep, it's rounded this way:

1. 100100 rounds down to `100k`, 100500 rounds up to `101k`. The thing is, the rounding is done, but the decimal part is stripped (unlike the four-digits rep).
    2. 100450 rounds down to `100k`, no step to round 450 to 500. Nor does 100499 - it's still `100k`.
    3. 279843 rounds up to `280k`, and 399999 rounds to `400k`.

As input, you're given the raw reputation, and output it as formatted.

You can consider that input **won't** receive any invalid numbers / non-numbers, or numbers with leading zeros, i.e. `0001234`.

Because Jon Skeet doesn't seem to be reaching 1,000,000 soon, ~~your code must be as short as possible~~ you don't need to handle the rep greater than one million (i.e. no special cases for 999500 and above).

# Answer
# Japt, ~~50~~ 48 bytes

First attempt; there may be a better method.

```
U<A³?U:U<L²?Us i1', :(U<1e5?Ue2n)r /A:Ue3n)r)+'k

```

Try it online!

### How it works

```
          // Implicit: U = input integer, A = 10, L = 100
U<A³?U    // If U is less than A³ (10³ = 1000), return U.
:U<L²?    // Else, if U is less than L² (100² = 10000), return:
Us i1',   //  U.toString, with a comma inserted at position 1.
:(        // Else, return:
U<1e5?    //  If U is less than 1e5:
Ue2n)     //   U * (10 to the power of -2),
r /A      //   rounded and divided by 10.
:Ue3n)r)  //  Else: U * (10 to the power of -3), rounded.
+'k       //  Either way, add a "k" to the end.
          // Implicit: output last expression

```
> 4 votes

# Answer
# JavaScript (ES6), ~~76~~ 68 bytes

```
x=>x<1e4?x.toLocaleString():(x<1e5?(x/1e2+.5|0)/10:(x/1e3+.5|0))+"k"

```

Another first attempt. Thank goodness for that handy `.toLocaleString()`, the shortest alternative I could find is 21 bytes longer...

This separates thousands by either `,` or `.`, depending on what country you live in. For ~~five~~ two bytes more, you can make it always use a comma:

```
x=>x<1e4?x.toLocaleString`en`:(x<1e5?(x/1e2+.5|0)/10:(x/1e3+.5|0))+"k"

```
> 7 votes

# Answer
# JavaScript (ES6), 71

~~Beating @ETHProductions while he does not see my hint.~~ He saw it.

```
x=>x<1e3?x:x<1e4?(x+='')[0]+','+x.slice(1):(x/1e3).toFixed(x<99950)+'k'

```

**Test**

```
f=x=>x<1e3?x:x<1e4?(x+='')[0]+','+x.slice(1):(x/1e3).toFixed(x<99950)+'k'

function test() { n=+I.value, O.textContent = n + ' -> ' + f(n) }

test()
```

```
<input id=I type=number value=19557 oninput=test()>
<pre id=O></pre>
```

**Test**
> 3 votes

# Answer
## ES6, ~~68~~ 62 bytes

```
x=>x<1e4?`${x}`.split(/(?=...)/)+"":x.toPrecision(3)/1e3+"k"

```

Edit: Saved 6 bytes when I realised that `["1", "001"]` stringifies to `"1,001"`.

Edit: Saved 2 bytes to fix @Mwr247's comment!
> 2 votes

# Answer
# Python 2.7, 58 bytes

```
lambda x:['%.3g'%((x+.5)/1e3)+'k','{:,}'.format(x)][x<1e4]

```

I had to use `(x+.5)` to deal with the `16950->17k` case..
> 1 votes

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


title: Unique multiplication by ten

text:
# Question
Title: Unique multiplication by ten
> People, it's a popularity contest, you have to do somthing cool here.
> Think about cool ways of breaking the code in most languages, not about validating for everyting!

> Initially this challenge is NOT for esoteric languages. But I didn't disabled them as I expect voters to be fair enough to downvote answers based only on esoteric language syntax uniqueness.

> It's not too broad. I thought about code golf tag, but desided that it will be unnessesary limitation for the answers. I expect anwsers to be short and exploiting some language feature.

> By the way, I have an interesting solution for VB.NET and it is shorter than 8 chars :)

---

Write a statement that multiplies the (integer) variable by 10 and assigns result to the same variable. If your language has no integer type, you may assume that the value is an integer not greater then some limit (you can specify this limit yourself, but it defenitly have to be adequate).

The initial and resulting values have to be number. Using string as one of them (or both) is forbidden.

But you don't want the code to be protable, so you are going to write it in such way, that the code is valid for **as *few* programming languages as possible**. Ideally in the only language.

Example:

> You have variable
>
> ```
> int x = 77;
>
> ```
>
> and the answer is
>
> ```
> x *= 10;
>
> ```

Declaration is not the part of the answer, only `x *= 10;` is.
So this code is valid for C, C++, C#, Java, Javascript and probably some other languages.
It's defenity a bad answer in this challenge.
Just drop a semicolon to cut off C, C++, C# and Java, but VB.NET appears in this case.

Scoring system: it's a popularity contest. For now I'll define the answer score as number of votes, but I'll keep a right to change scoring system by including number of languages into it.

So you have to provide a statement and list of languages (ideally one language) it is valid in.

# Answer
> 1 votes
In Perl you can do:

```
$var .= 0;

```

because it is not typed.

or

```
$var =~ s/$/0/;

```

Regex that adds a zero at the end of line.

# Answer
> 0 votes
# Vitsy, 2 bytes

```
a*
```

Call this method through any normal means (00k or 0m). The top item of the stack will be multiplied by 10 (a in hexadecimal). This is very anti-polyglot because most stack based languages don't *have* methodology.

---
Tags: popularity-contest, restricted-source
---


title: Let's see some action!

text:
# Question
Title: Let's see some action!
Who doesn't love action movies with fast noisy cars, especially those with a lot of crashes? Who doesn't love action shots in ascii art?

# The scene is:

Two cars are starting at opposite sides of a straight road (with 60 spaces between). They start driving towards each other at constant speeds. The car to the left drives at 1 space per second, and the one to the right drives at 2 spaces per second.

Obviously, the cars can't pass through each other, so for `n ≥ 20`, the scene will be two crashed cars with bonnets up at the position where the crash occurred.

As a movie lover, I want to pause the scene now and then, just to enjoy the beauty of it.

Given an integer `n` (function argument or STDIN), representing the number of seconds from the start of the scene, show the scene at that moment.

This is the starting scene, with 60 spaces between the front wheels:

```
  __                                                                __
_/  \_                                                            _/  \_
o    o                                                            o    o

```

this is the scene after 11 seconds:

```
             __                               __
           _/  \_                           _/  \_
           o    o                           o    o

```

and this is what it looks like after the crash (note that the bonnets are up after the crash):

```
                      __    __
                    _/  \/\/  \_
                    o    oo    o

```

I'm only interested in watching two cars crashing, so spaces, newlines, ++ doesn't matter.

This is code golf, so the shortest code in bytes wins. Answers added later can still win if they are shorter than the current accepted answer.

# Answer
# CJam, ~~68~~ 66 bytes

```
liKe<:M"  __  _/  \_o    o"6/f{\S*1$+60M3*-S*@N}:+MK={58'/t59'\t}&

```

Try it online

Anybody who sees the start of the code will be sure to `liKe` it!

Explanation:

```
li      Get input n and convert to integer.
Ke<     Cap n at 20.
:M      Save in variable M for multiple use later.
"  __  _/  \_o    o"
        Car (18 characters).
6/      Split into 3 lines of 6 characters.
f{      Map lines with parameter.
  \       Swap n to top.
  S*      Create string with n spaces for left margin.
  1$      Copy one car line to top. Keep original for second car
  +       Concatenate the spaces and car.
  60M3*-  Calculate 60-3*n, which is the amount of space between cars.
  S*      Create string with 60-3*n spaces.
  N       Add a newline.
}       End of line mapping.
:+      Concatenate all output pieces into single string.
MK=     Check if capped n is equal to 20.
{       If equal, replace hoods with crashed versions.
  58'/t   '/ at position 58.
  59'\t   '\ at position 59.
}&      End of conditional block for crashed hoods.

```
> 10 votes

# Answer
# Labyrinth, ~~394~~ 386 bytes

I proudly introduce...

```
<}74}}:23}29}59}}}}}}}:111_}}}}:::::::23_}:111
?                        @
:" }}_47}_95    3""""""""(
 _ :       }    _   }    {=}
 2 23_}29_ _    ;   :      \
 0       ; 3  +_( 3_"  60{ .{.{.
"-_95:}}"" 2  0 ) 2 "  _ _ {
""       _ :  2 _ ."(; } 3 .{
 ;_92}_47} :  _ 0    = : *  ;
           : "" 2 {.{{ . -""(
}}:59_}}:::: "";_ .    {  _ "
}             "   {.{.{.  32.
}}}_95:}}}}_20-

```

...my new two-dimensional esolang Labyrinth! The code above isn't incredibly well golfed (there are 161 spaces and 25 NOPs, so a better layout could shorten this a lot), but at least I managed to show that the language is usable for non-trivial tasks. :)

## How it works

First, a quick overview of the language:

* Labyrinth operates on two stacks, *main* and *auxiliary*, which can hold arbitrary signed integers. At the bottom of both stacks there is an infinite amount of zeroes.
* Commands are individual characters on a 2D grid and they form a maze (that is unknown characters, particularly spaces, are walls). `"` is a NOP which is not a wall and can be helpful for padding certain paths in the code. As opposed to many other 2D languages, the edges do *not* wrap around.
* The instruction pointer (IP) starts at the first non-wall character (in reading order) moving to the right. `@` terminates the program.
* If possible, the IP follows corridors (also around bends). If the IP has multiple cells to move to, it will generally turn left if the top of the main stack is negative, move straight ahead if it's zero, or turn right if it's positive. When the IP hits a wall it reverses direction. (There are a few more subtleties, but they shouldn't matter for this code.) This is the only way to implement control flow.
* Apart from arithmetic and stack manipulation commands, the source code can be modified at runtime with the four commands `>v<^` which will shift a row or column of the source code cyclically by one cell. Which row or column is affected depends on the top of the stack. If the IP's own row or column is shifted, it will move with the shift. This makes it possible to jump from one edge of the source code to the other.

Now for this particular challenge, here is the general idea of the algorithm:

* Push the ends of the cars up to the bonnets (i.e. `/ \_o oo o`) onto the auxiliary stack.
* Read the input and determine whether to push `__` or `/\` next.
* Push the remainder of the cars (i.e. `__ __ _/ \` and two leading spaces) onto the auxiliary stack.
* Clamp the input to a maximum value of `20`, let's call this *N*.
* Now do the following 3 times:
    + Print *N* spaces.
    + Print 6 stored characters.
    + Print 60 - 3\**N* spaces.
    + Print 6 stored characters.
    + Print a newline.

Finally, let's look at some parts of the code. The IP starts in the top left corner, on a grid shifting command. The top of the main stack is `0` (which is used as a relative index), so the first row is shifted to the left, which also moves the IP to the right end of the grid. Now the first row is simply executed from right to left, which pushes the first set of fixed characters onto the auxiliary stack:

```
}74}}:23}29}59}}}}}}}:111_}}}}:::::::23_}:111<

```

This row shifting is useful for golfing when you want to start with a large amount of linear code.

Next we read the input and push the correct bonnets:

```
?
:"
 _
 2
 0       ;
"-_95:}}""
""       _
 ;_92}_47}

```

The bit on the left with the three NOPs sends negative results along the top branch and non-negative results along the bottom branch. At the right they are joined back together.

Now follows another large linear section (which could probably be golfed a lot with another row-shifting trick):

```
   }}_47}_95
   :       }
   23_}29_ _
           3
           2
           :
           :
           :
}}:59_}}::::
}
}}}_95:}}}}

```

This pushes the remainder of the cars onto the auxiliary stack.

Next, we compute `min(20, input)`, which is similar to first branch:

```
                ;
              +_(
              0 )
              2 _
              _ 0
             "" 2
             "";_
              "
           _20-

```

Finally, we have the loop which runs three times to print the lines. Each iteration of the loop contains two small (3x3) loops to print the spaces, as well as two sections to print 6 characters from the auxiliary stack:

```
                         @
                3""""""""(
                _   }    {=}
                    :      \
                  3_"  60{ .{.{.
                  2 "  _ _ {
                  ."(; } 3 .{
                     = : *  ;
                  {.{{ . -""(
                  .    {  _ "
                  {.{.{.  32.

```

One nifty trick I'd like to draw attention to is the `.{.{.` at the right edge. This is a dead end, so apart from the `.` at the end the code is executed twice, once forward and once backward. This gives a neat way to shorten palindromic code (the catch is that you need to make sure the IP takes the correct turn when exiting the dead end again).
> 14 votes

# Answer
## Python 2.7, ~~167~~ ~~164~~ 159 Bytes

```
n=input();s,x=60-3*n,min(n,20)
for e in['  _',"_/ ","o  "]:p=e+(e[::-1],(' \_',' \/')[s<1])['/'in e];print" "*x+p+" "*s+(p[-1]+p[1:-1]+p[0]).replace("//","\/")

```

This takes input from stdin.
Demo here
Testing this -

```
$ ./cars.py
0
  __                                                                __
_/  \_                                                            _/  \_
o    o                                                            o    o

$ ./cars.py
11
             __                               __
           _/  \_                           _/  \_
           o    o                           o    o

$ ./cars.py
20
                      __    __
                    _/  \/\/  \_
                    o    oo    o

```
> 7 votes

# Answer
# R, 191 Bytes

About as good as I can get it now. Takes the seconds from STDIN and cats to STDOUT.

```
n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s  __  %s  __  ','%s_/  \\_%s_/  \\_','%s_/  \\/%s\\/  \\_','%so    o%so    o')[-3+(n<21)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')

```

Explanation

```
# Get the input from STDIN.  Requires a single number 0-20
n=scan();
# alias paste0 and set collapse default to ''
p=paste0;
formals(p)$collapse='';
# output
cat(
    # sprintf to format the strings
    sprintf(
        # vector of strings to format                                                      picks which bonnet to remove
        c('%s  __  %s  __  ','%s_/  \\_%s_/  \\_','%s_/  \\/%s\\/  \\_','%so    o%so    o')[-3+(n<21)]
        # move left car by 1
        ,p(rep(' ',n))
        # move right car by 2
        ,p(rep(' ',60-n*3))
    )
,sep='\n')

```

Tests

```
> n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s  __  %s  __  ','%s_/  \\_%s_/  \\_','%s_/  \\/%s\\/  \\_','%so    o%so    o')[-3+(n==20)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
1: 0
2:
Read 1 item
  __                                                                __
_/  \_                                                            _/  \_
o    o                                                            o    o
> n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s  __  %s  __  ','%s_/  \\_%s_/  \\_','%s_/  \\/%s\\/  \\_','%so    o%so    o')[-3+(n==20)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
1: 5
2:
Read 1 item
       __                                                 __
     _/  \_                                             _/  \_
     o    o                                             o    o
> n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s  __  %s  __  ','%s_/  \\_%s_/  \\_','%s_/  \\/%s\\/  \\_','%so    o%so    o')[-3+(n==20)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
1: 20
2:
Read 1 item
                      __    __
                    _/  \/\/  \_
                    o    oo    o
>

```
> 5 votes

# Answer
# PHP, 160 155 bytes

```
$f=str_repeat;echo$l=$f(' ',$s=min(max($argv[1],0),20)),"  __  ",
$m=$f(' ',$r=60-3*$s),"  __\n{$l}_/  \\",$r?_.$m._:'/\\',
"/  \\_\n{$l}o    o{$m}o    o\n";

```

The code is displayed here on 3 lines to fit the layout of the code box. Those newlines are not needed.

The ungolfed code:

```
// The number of seconds, between (and including) 0 and 20
$sec  = min(max($argv[1], 0), 20);
$rest = 60 - 3 * $sec;

$left = str_repeat(' ', $sec);      // left padding
$mid  = str_repeat(' ', $rest);     // space in the middle
$c = $rest ? '_'.$mid.'_' : '/\\';

echo($left.'  __  '.$mid."  __\n");
echo($left.'_/  \\'. $c ."/  \\_\n");
echo($left.'o    o'.$mid."o    o\n");

```

It gets the number of seconds from the command line (first argument):

```
$ php -d error_reporting=0 action.php 11
             __                               __
           _/  \_                           _/  \_
           o    o                           o    o

```

The PHP CLI option `-d error_reporting=0` is needed to hide some notices PHP displays about undefined constants (`str_repeat`, `_`) that it converts to strings (2 bytes saved for each notice).

One additional byte can be saved on PHP 7 by squeezing the initialization of `$f` into its first use (`$m=($f=str_repeat)(...)`); it doesn't compile on PHP 5.

The test case and some of the techniques used to shrink the code can be found on github.

**Update:**

@ismail-miguel squeezed the initialization of `$left` and inlined `$c` into the arguments of `echo` saving 4 bytes (see comment below).

By swapping the order the variables `$m` and `s` are initialized I got rid of a pair of parentheses and saved 1 byte more.
> 4 votes

# Answer
## CJam, 120 bytes

```
q~20e<_["   "]*\[" _o"]\[" / " "_  " "_  " " \ " ]\[19>" /o"" _o"?]60 3 5$,*-["   "]*[0$," _o"" \o"?]3$[" _o"]+++++++zN*

```

Demo

Ungolfed:

```
q~        e# Read the input
20e<      e# min(20, input) (let's call it N)
_         e# Duplicate the value on the stack
["   "]   e# Push 3 blank spaces
*         e# Create N arrays of 3 blank spaces
\         e# Swap the top two stack elements
[" _o"]   e# Push the " _o" string to stack
\         e# Swap the top two stack elements
[" / " "_  " "_  " " \ " ]
\         e#
[         e# If N is greater than 20 then push the array [" /o"],
  19      e# otherwise [" _o"]
  >
  " /o"
  " _o"
  ?
]
60        e# 60 is the maximum space between the two cars
3         e# 3 is the number of blocks covered per move
5$,       e# Take the 6th element from the stack (an array of size N)
*-        e# Compute the remaining blocks (60 - 3 * N)
["   "]   e# Add an array of 3 blank spaces
*         e# Multiply it to fit the remaining blocks
[0$," _o"" \o"?] e# Add the (broken?) front part of the second car
3$        e# Copy the middle part of the car
[" _o"]   e# Append the right side of the car
+++++++   e# Concatenate all arrays
z         e# Transpose the array
N*        e# Join the array using new lines

```

Demo
> 4 votes

# Answer
# JavaScript (ES6), 121 bytes

Using template string, the 2 newlines inside the string are signficant and counted.

To save bytes, output with `alert`, even if the proportional font used in `alert` is not well suited for ASCII art and the result is ugly for n\>=20 (crash).

Test running the snippet in FireFox

```
F=n=>alert(`  __
_/  \\_
o    o`.replace(/.+/g,v=>(Z=x=>' '.repeat(x)+v)(n<20?n:n=20)+Z(60-3*n)).replace('__/','/\\/'))
```

```
<input id=I value=10><button onclick='F(I.value)'>go</button>
```
> 3 votes

# Answer
# C, ~~180~~ ~~191~~ 168 bytes

```
#define S(x,y)"  __  ",#x"/  \\"#y,"o    o",
char*s[][3]={S(_,_)S(_,/)S(\\,_)};i;l;f(n){l=n>19&&(n=20);for(i=0;i<3;i++)printf("%*s%*s\n",n+6,s[l][i],60-3*n,s[l*2][i]);}

```

ungolfed:

```
// make a map of possible car parts
#define S(x, y) { "  __  ", #x "/  \\" #y, "o    o" }
char * s[4][3]= {
    S(_,_),
    S(_,/),
    S(\\,_)
};
i,l;
f(n){
    i = 0;
    l = n>19 && (n = 20); // l = 1, if crash happend
    for(; i < 3; i++) {
        // '*' means length (padding) is given as an int argument
        printf("%*s%*s\n", n + 6, s[l][i], 60 - 3 * n, s[l*2][i]);
    }
}

```

test program:

```
main() {
    f( 0);f( 5);f(10);
    f(15);f(20);f(21);
    return 0;
}

```

output:

```
  __                                                          __
_/  \_                                                      _/  \_
o    o                                                      o    o
       __                                           __
     _/  \_                                       _/  \_
     o    o                                       o    o
            __                            __
          _/  \_                        _/  \_
          o    o                        o    o
                 __             __
               _/  \_         _/  \_
               o    o         o    o
                      __    __
                    _/  \/\/  \_
                    o    oo    o
                      __    __
                    _/  \/\/  \_
                    o    oo    o

```

I was able to golf this one pretty hard. I think I started with almost 300 bytes.

~~But I don't know if this still fulfills all the requirements. As you can see after 21 seconds, the first car pushes the second car over to the right. I would need to add a few bytes if this isn't allowed.~~

**Edit:** fixed it. This should be more realistic than Sharknado ;-)

**Edit:** I could significantly shorten my solution by taking a second look at the `printf` man-page. If you use '\*' you can supply the field length directly to printf, without the need to create a format-string with `sprintf` beforehand.
> 2 votes

# Answer
# Python 2, 148 bytes

This uses ANSI escape codes to position the cursor in the right place to draw the cars. It then checks to see if the input was 20, if it was, it goes back and draws on the bonnets of the car.

Takes an int from stdin, output to stdout.

```
p=lambda x:"u  __u_/  \_uo    o".replace("u","\n\033[%dC")%(x,x,x)+"\033[4A";i=min(20,input());print p(i)+"\n"+p(66-i*2)+"\n\n\n\033[25C/\\"*(i==20)

```

Ungolfed:

```
def get_car(x):
    return "\n  __\n_/  \_\no    o".replace("\n","\n\033[%dC")%(x,x,x)+"\033[4A"

i=min(20,input())
print get_car(i)
print get_car(66-i*2)
if i==20:
    print"\n\n\033[25C/\\"

```
> 2 votes

# Answer
## Pyth, 67 bytes

```
Kjbm+++*\ JhS,Q20d*\ -60*3Jdc3"  __  _/  \_o    o"?nJ20KXXK58\/59\\

```

Try it out here.

```
                                                                       Implicit: Q=eval(input())
          JhS,Q20                                                      Set J=min(Q,20)
                              "  __  _/  \_o    o"                     Concatenated car string
                            c3                                         Split into 3
   m                                                                   For d in the above
       *\ J                                                            J spaces before 1st car
                  *\ -60*3                                             60-3J spaces in between them
    +++          d         d                                           Concatenate spaces and car string
Kjb                                                                    Join on newlines, store in K
                                                  ?nJ20                If J != 20...
                                                       K               ... print K
                                                         XK58\/        ... else put / in position 58
                                                        X      59\\        and \ in position 59 (implicit print)

```
> 2 votes

# Answer
## Python 2, 102 bytes

```
n=input()
for r in"  __  ","_/  \_","o    o":print((n*' ')[:20]+r+(60-3*n)*' '+r).replace('__/','/\/')

```

Pretty straightforward. For each row of the car, we print `n` spaces, that row, `60-3*n` spaces, and the row again. To stop the cars, rather than doing `min(n,20)`, it was one char shorter to limit the first run of spaces with `[:20]`, and the second is fine because a negative times a string is the empty string.

To move up the fenders, we just do a `replace`. Since `__` also appears on the roof, we need a bit of context to identify the fenders, so we check for a `/` following.
> 2 votes

# Answer
# \>\<\>, ~~538~~ 276 bytes

```
 :3*a6*$-:0)?v~~a2*0c4*1-e2*1+6pa9*2+b7p04.
  v          >04.
 >>1[>:0)  ?v~].
  ^  ^-1o" "<
\$:&94&12." ":oo"_":oo" ":oo
\$:&95&12." ":oo"_":oo" ":ooao
\$:&96&12."_"o"/"o" ":oo"\"o"_"o
\$:&97&12."_"o"/"o" ":oo"\"o"_"oao
\$:&98&12."o"o" ":::oooo"o"o
\$:&99&12."o"o" ":::oooo"o"o;

```

I've dropped the size a LOT, I'm amazed that I managed to drop the size by half. The old one is below. This one is not as efficient performance wise due to the width of the grid, mostly from the very first line.

You can test it out here. Put the amount of time passed in the "Initial Stack", not "Input"!

Here's the old version.

```
:3*a6*$-:0)  ?v~~a2*0c4*1-c3*1-4p^
v~v?)0:  <[1:$/$:1[ >:0)  ?v~]" ":oo"_":oo" ":ooaov
] >" "o1-^    ^    <^-1o" "/"/"o"_"<]~v?)0:  <[1:$<
>" ":oo"_":oo" ":oo^       \o" ":oo"\"\" "o1-^
/o"\"oo:" "o"/"o"_"]~v?)0:  <[1:$o"_"o/
\"_"oaov   hi there  >" "o1-^
       >$:1[ >:0)  ?v~]"o"o" ":::oooo"o"o>$:1[ >:0)  ?v~]v
       ^    <^-1o" "<                    ^    <^-1o" "<
              v      p4-1*29+2*9a<    ;o"o"oooo:::" "o"o"<

```
> 2 votes

# Answer
## Java, 258 Chars

```
class M{public static void main(String[]a){String l="",m=l,r="  __  ",w="o    o",x="_/  \\_";int p=Integer.parseInt(a[0]),i=20;p=p>i?i:p;for(i=-1;++i<p;)l+=" ";for(;++i<21;)m+="   ";System.out.print(l+r+m+r+"\n"+l+(x+m+x).replace("__","/\\")+"\n"+l+w+m+w);}}

```

Un-Golfed

```
  class M {
     public static void main(String[] a) {
        String l = "", m = l, r = "  __  ", w = "o    o", x = "_/  \\_";
        int p = Integer.parseInt(a[0]), i = 20;
        p = p > i ? i : p;
        for (i = -1; ++i < p;)
           l += " ";
        for (; ++i < 21;)
           m += "   ";
        System.out.print(l + r + m + r + "\n"
              + l + (x + m + x).replace("__", "/\\") + "\n"
              + l + w + m + w);
     }
  }

```

Results

```
0
  __                                                                __
_/  \_                                                            _/  \_
o    o                                                            o    o

1
   __                                                             __
 _/  \_                                                         _/  \_
 o    o                                                         o    o

...

19
                     __       __
                   _/  \_   _/  \_
                   o    o   o    o

20
                      __    __
                    _/  \/\/  \_
                    o    oo    o

21
                      __    __
                    _/  \/\/  \_
                    o    oo    o

```
> 2 votes

# Answer
# Java, 270 267 bytes

Pretty sure there's a better/shorter way of doing this, but my brain isn't properly engaged.

```
class C{public static void main(String[]a){String l="",m="",r="  __  ",w="o    o";int p=Math.min(Integer.parseInt(a[0]),20),i;for(i=0;++i<p;)l+=" ";for(i=0;++i<60-3*p;)m+=" ";System.out.print(l+r+m+r+"\n"+l+"_/  \\"+(p==20?"/"+m+"\\":"_"+m+"_")+"/  \\_\n"+l+w+m+w);}}

```

**For n=19:**

```
                    __      __
                  _/  \_  _/  \_
                  o    o  o    o

```

**For n=20:**

```
                     __    __
                   _/  \/\/  \_
                   o    oo    o

```

**Ungolfed**

```

public class Crash {
public static void main(String[] args) {
    String left="", mid="", r="  __  ", w="o    o";
    int pos = Math.min(Integer.parseInt(args[0]),20),i;
    for (i=0; ++i<pos;){
        left+=" ";
    }
    for (i=0; ++i<60-3*pos;){
        mid+=" ";
    }
    System.out.print(
            left + r + mid + r + "\n" +
            left + "_/  \\" + (pos==20 ? "/" + mid + "\\" : "_" + mid + "_") + "/  \\_\n" +
            left + w + mid + w);
}
}

```
> 1 votes

# Answer
# Javascript, 193 bytes

It's not a winner, but it's something

http://jsfiddle.net/yb703y0p/2/

```
function f(n){
c = ["  __  A", "_/  \\_A", "o    oA"]
for(i=0;i<3;i++)c[i]=c[i].replace('A',' '.repeat(n))+c[i].replace('A','')
if(n==0)c[1]=c[1].replace('__','/\\')
console.log(c.join("\n"))
}

```
> 1 votes

# Answer
# PHP 7, 140 bytes

```
<?$s=$argv[1];$r=($f=str_repeat)(~ß,60-3*$s);echo$l=$f(~ß,min(20,$s)),"  __  $r  __
${l}_/  \\",$r?_.$r._:~Ð£,"/  \_
$l",$o=~ßßßß,$r,$o;

```

### Usage:

Save as ANSI in `file.php` (there should be zero-width characters in `$o`) and run:

```
php -derror_reporting=~E_NOTICE -dshort_open_tag=1 file.php x

```

with `x` as the number of seconds.

And a version that works without changing the error reporting (**148 bytes**):

```
<?$s=$argv[1];$r=($f=@str_repeat)(' ',60-3*$s);echo$l=$f(' ',min(20,$s)),"  __  $r  __
${l}_/  \\",$r?"_${r}_":"/\\","/  \_
$l",$o="o    o",$r,$o;

```
> 1 votes

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


title: Tokenize a Stack-Based language

text:
# Question
Title: Tokenize a Stack-Based language
I've been working on *another* stack-based golfing language called Stackgoat. In this challenge you'll be writing a Tokenizer for Stackgoat (or really any general stack-based languages).

## Examples

```
"PPCG"23+
["PPCG", '23', '+']

'a "bc" +
['"a"', '"bc"', '+']

12 34+-"abc\"de'fg\\"
['12', '34', '+', '-', '"abc\"de'fg\\"']

"foo
['"foo"']

(empty input)
[]

' ""
['" "', '""']

```

## Specification

The three types you'll need to handle are:

* Strings, *anything* within `""`
* Numbers, any sequence of digits
* Operators, any other single character besides whitespace

Whitespace is essentially ignored unless it is within a string or separates two numbers.

String / char spec:

* Strings are delimited by a `"`, and when a `\` is encountered, the next character should be escaped.
* Chars are prepended by a `'` and the character after the `'` should be converted into a string literal. `'a` -\> `"a"`
* `'` will always have a character after it
* Closing quotes should be auto-inserted

Rules:

* No form of `eval` is allowed

Input / Output:

* Input can be taken through STDIN, function parameters, or your language's equivalent.
* Output should be an array or your language's closest equivalent.

# Answer
> 8 votes
## Retina, ~~68~~ ~~64~~ 63 bytes

```
M!s`"(\\.|[^"])*"?|'.|\d+|\S
ms`^'(.)|^"(([^\\"]|\\.)*$)
"$1$2"

```

or

```
s`\s*((")(\\.|[^"])*(?<-2>")?|'.|\d+|.)\s*
$1$2¶
\ms`^'(.)
"$1"

```

I think this covers all the funky edge cases, even those not covered by the test cases in the challenge.

Try it online!

# Answer
> 2 votes
### Ruby, 234 bytes

```
puts"[#{$stdin.read.scan(/("(?:(?<!\\)\\"|[^"])+(?:"|$))|'(.)|(\d+)|(.)/).map{|m|(m[0]?(m[0].end_with?('"')?m[0]: m[0]+'"'): m[1]?"\"#{m[1]}\"": m.compact[0]).strip}.reject(&:empty?).map{|i|"'#{/\d+|./=~i ?i: i.inspect}'"}.join', '}]"

```

I tried using the `find(&:itself)` trick that I saw... somewhere, but apparently `.itself` isn't actually a method. Also, I'm working on golfing the regex down, but it's already unreadable.

If we don't have to output in any fancy way (i.e. strings don't have to be quoted in the array) I can save a whole lotta bytes:

### Still Ruby, 194 bytes:

```
p$stdin.read.scan(/("(?:(?<!\\)\\"|[^"])+(?:"|$))|'(.)|(\d+)|(.)/).map{|m|(m[0]?(m[0].end_with?('"')?m[0]: m[0]+'"').gsub(/\\(.)/,'\1'): m[1]?"\"#{m[1]}\"": m.compact[0]).strip}.reject(&:empty?)

```

I'm sure I can golf it more, but I'm not quite sure how.

---

Ungolfed coming soon. I started fiddling with the golfed directly at some point and I'll have to tease it out.

# Answer
> 0 votes
# Python 3, 228 bytes

```
import re;L=list
print(L(map(lambda i:i+'"'if i[0]=='"'and not i[-1]=='"'else i,map(lambda i:'"%s"'%i[1]if i[0]=="'"else i,filter(None,sum([L(i)for i in re.findall('(\'.)|(".*")|(\d+)|([^\w\"\'\s\\\])|(".*"?)',input())],[]))))))

```

Here's a nice, long, two-liner.

---

Test it out in Python 3. Here's some examples:

```
$ python3 test.py
"PPCG"23+
['"PPCG"', '23', '+']

$ python3 test.py
'a "bc" +
['"a"', '"bc"', '+']

$ python3 test.py
12 34+-"abc"de'fg\"
['12', '34', '+', '-', '"abc"de\'fg\\"']

$ python3 test.py
"foo
['"foo"']

$ python3 test.py

[]

$ python3 test.py
' ""
['" "', '""']

```

---
Tags: code-golf, parsing
---